Question

I got two bytes:

byte[0] is 0000 0000

byte[1] is 1000 0000

I would like to put them together and make one float value of them. So the result should be 128 is decimal and 0000 0000 1000 0000 in binary. Not negative because of the leading zero.

My solution so far is this approach:

float f = (bytes[0] << 8 | bytes[1]);

But this will result in a value of minus 128 for value f. It's because of the 2s complement i guess. Therefore byte[1] will be interpreted as negative. How can I just see the leading bit of byte[0] as the bit for negative/positive?

Was it helpful?

Solution

Try this:

short int16 = (short)(((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF));

You need to use parenthesis because of operation precedence.

once you have your 16 bit integer, you can assign it to your float:

float f = int16;

yes, you could have done it in one step, but I wanted to go step by step.

OTHER TIPS

Since you are performing some widening conversions, you have to stop the propagation of leading 1 bits due to the internal usage of two's complement:

byte[] bytes = {0, -128}; // bytes[0] = 0000 0000, bytes[1] = 1000 0000
short s = (short) (((bytes[0] & 0xFF) << 8) | (bytes[1] & 0xFF));
System.out.println(s); // prints 128

Also, float is for floating point numbers, since you want a 16 bit decimal number I changed the target datatype to short.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top