Python 浮点到IEEE-754,分为两个16位字
我需要以两个单词(每个单词是16位)作为Python浮点的IEEE-754表示形式结束。 这些单词需要作为int传递给函数 当我做我现在使用的东西时,我有时会得到太大的INTPython 浮点到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
溢出错误: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
是一个常规的Pythonfloat
);看见我很高兴我从来没有学过粒子物理学。谢谢,这就是我想要的