Two 16 bit ints to One 32 bit float value

随声附和 提交于 2020-01-07 04:37:19

问题


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:

  • int + int = float
  • 0 + 16256 = 1
  • 0 + 17096 = 100
  • 0 + 17097 = 100.5
  • 0 + 17530 = 1000
  • 8192 + 17530 = 1000.5

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


回答1:


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.



来源:https://stackoverflow.com/questions/43908820/two-16-bit-ints-to-one-32-bit-float-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!