Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 浮点到IEEE-754,分为两个16位字_Python_Floating Point_Type Conversion_Byte - Fatal编程技术网

Python 浮点到IEEE-754,分为两个16位字

Python 浮点到IEEE-754,分为两个16位字,python,floating-point,type-conversion,byte,Python,Floating Point,Type Conversion,Byte,我需要以两个单词(每个单词是16位)作为Python浮点的IEEE-754表示形式结束。 这些单词需要作为int传递给函数 当我做我现在使用的东西时,我有时会得到太大的INT 溢出错误:Python int太大,无法转换为C long 这是我现在使用的代码: def floatToWords(self, value): s = struct.pack('f', value).encode('hex') word1 = int(s, 16) word

我需要以两个单词(每个单词是16位)作为Python浮点的IEEE-754表示形式结束。 这些单词需要作为int传递给函数

当我做我现在使用的东西时,我有时会得到太大的INT

溢出错误:Python int太大,无法转换为C long

这是我现在使用的代码:

def floatToWords(self, value):
        s = struct.pack('f', value).encode('hex')
        word1 = int(s, 16)
        word2 = int(s[2:4], 16)
        return word1, word2

words = self.floatToWords(concentration)
modbus.write_input_register(self.modbusAddress['concentration'],   words[0])
modbus.write_input_register(self.modbusAddress['concentration']+1, words[1])
我转换的正确吗


PS:Python2.6

我有充分的理由认为正确的方法是

word1, word2 = struct.unpack('>HH', struct.pack('>f', value))

我曾经在IEEE754上写过一篇文章,它给出了兼容的结果。

试着用
word1=int(s[0:2],16)
@martineau:应该是
int(s[0:4],16)
(和
int(s[4:8],16)
作为第二个词。我遗漏了什么?据我所知,Python不支持单精度。IEEE-754双工是64位的。是不是你想转换成32位的IEEE-754,然后将其拆分?@BillBell:我想是的。请注意,Python的
struct.pack('>f',value)
确实将
value
隐式转换为单精度(假设
value
是一个常规的Python
float
);看见我很高兴我从来没有学过粒子物理学。谢谢,这就是我想要的