[英]Convert 64-bits floating-point format string to floating-point number
I have a bunch of 64-bit floating-point-format strings, and I have to convert them into floating-point numbers. 我有一堆64位浮点格式的字符串,我必须将它们转换为浮点数。 I know what the format looks like, but I'm wondering whether there's a built-in function can fulfill this job directly, as in:
我知道格式是什么样子,但是我想知道是否有内置函数可以直接完成这项工作,例如:
convertToFloat(C06FCA5E35000000) --> -254.324
convertToFloat(405F7D70A4000000) --> +125.96
I know how to convert these bit patterns to numbers manually, but it needs a lot of bit shifting. 我知道如何手动将这些位模式转换为数字,但是它需要大量的移位。 Is there a better way?
有没有更好的办法?
I modified 'C06FCA5E35000000' to '\\xC0\\x6F\\xCA\\x5E\\x35\\x00\\x00\\x00', and stored it to myString. 我将'C06FCA5E35000000'修改为'\\ xC0 \\ x6F \\ xCA \\ x5E \\ x35 \\ x00 \\ x00 \\ x00',并将其存储到myString中。
>>>print (myString)
\xC0\x6F\xCA\x5E\x35\x00\x00\x00
>>>d = struct.unpack('>d', myString)
d = struct.unpack('>d', myString)
struct.error: unpack requires a string argument of length 8
Why did it happened? 为什么会发生?
I didn't use binascii.a2b_hex or binascii.b2a_hex, beacuse it converts 'A' to '41' or '41' to 'A'. 我没有使用binascii.a2b_hex或binascii.b2a_hex,因为它会将'A'转换为'41'或将'41'转换为'A'。 Both are not what I want.
两者都不是我想要的。 Right?
对?
>>>print len('\xC0\x6F\xCA\x5E\x35\x00\x00\x00')
8
>>>print len(myString)
32
Now I know why it happened, but I still don't know how to solve the situation. 现在我知道为什么会这样,但是我仍然不知道如何解决这种情况。
You can use struct.unpack
. 您可以使用
struct.unpack
。 >d
is a big-endian double; >d
是大尾数双; see help(struct)
for more! 看到
help(struct)
更多!
import struct
d, = struct.unpack('>d', b'\xc0\x6f\xca\x5e\x35\x00\x00\x00')
print(d)
# -254.32399988174438
If your string is really 'C06FCA5E35000000'
, you can convert it first into bytes using binascii.a2b_hex
. 如果您的字符串确实是
'C06FCA5E35000000'
,则可以使用binascii.a2b_hex
首先将其转换为字节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.