Python: convert 2 ints to 32 float

匿名 (未验证) 提交于 2019-12-03 02:19:01

问题:

How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into 2 16 bit ints?

(I need this because of modbus protocol - where 2x16 bit registers are treated as single 32 floating point number)

回答1:

This code takes the 16 bits integers i1 and i2 and convert them to the floating point number 3.14, and vice versa.

from struct import * # Two integers to a floating point i1 = 0xC3F5 i2 = 0x4840 f = unpack('f',pack('>HH',i1,i2))[0]  # Floating point to two integers i1, i2 = unpack('>HH',pack('f',3.14)) 


回答2:

The standard struct module can be used to do this easily. Just be careful of your platform endianess but, other than that, it should be a pretty straight-forward application of pack() and unpack().



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