JensD
JensD

Reputation: 195

Two 16 bit ints to One 32 bit float value

I am able to extract values from modbus as 16-bit shorts (unsigned) or as ints (should be treated as 16-bit words). I am tasked to combine two values to create a single 32 bit float value using java.

some example values I observed using a gui program:

I attempted bit wise operators but that didn't seem to do the trick. leaves me scratching my head!

Upvotes: 0

Views: 8037

Answers (1)

Eran
Eran

Reputation: 393966

You can use Float.intBitsToFloat(int bits) to build a float from the bits of an int.

short high = ... // the high 16 bits
short low = ... // the low 16 bits
int combined = (high << 16) | low;
float num = Float.intBitsToFloat(combined);

for example:

short high = 17530;
short low = 8192;

produces the float 1000.5.

Upvotes: 2

Related Questions