user3668129
user3668129

Reputation: 4820

How to put unsigned float into ByteBuffer?

I'm trying to handle unsigned primitives number with ByteBuffer.

I can handle (put into ByteBuffer) unsigned byte/short/int. For example, the code to handle unsigned int:

m_buf.putInt(nOffset, (int) (0xFFFFFFFF & number.longValue()));

but, when I want to do the same for unsigned float:

m_buf.putFloat(nOffset, (float) (0xFFFFFFFF & number.doubleValue()));

I'm getting compiler error: "The operator & is undefined for the argument type(s) int, double"

So - How can I handle get and set unsigned float number with ByteBuffer?

Thanks

Upvotes: 1

Views: 361

Answers (2)

Tkachuk_Evgen
Tkachuk_Evgen

Reputation: 1354

You can't use bitwise & with floating point numbers. Try this:

m_buf.putFloat(nOffset, Float.valueOf(0xFFFFFFFF & number));

Upvotes: -1

aioobe
aioobe

Reputation: 421220

The IEEE 754 floating point representation has 1 bit reserved for the sign. There is no alternative representation that uses this bit as part of the mantissa or exponent. In other words, there is no "unsigned float".

If all you want to do is to make sure you don't put any negative numbers in the buffer, just do

m_buf.putFloat(nOffset, Math.abs(number.floatValue()));

Upvotes: 2

Related Questions