我有一堆64位浮点格式字符串,我必须将它们转换为浮点数。 我知道格式是什么样的,但我想知道是否有内置函数可以直接完成这项工作,如:
convertToFloat(C06FCA5E35000000) --> -254.324 convertToFloat(405F7D70A4000000) --> +125.96我知道如何手动将这些位模式转换为数字,但它需要大量的位移。 有没有更好的办法?
我将'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为什么会这样?
我没有使用binascii.a2b_hex或binascii.b2a_hex,因为它将'A'转换为'41'或'41'为'A'。 两者都不是我想要的。 对?
>>>print len('\xC0\x6F\xCA\x5E\x35\x00\x00\x00') 8 >>>print len(myString) 32现在我知道它为什么会发生,但我仍然不知道如何解决这个问题。
I have a bunch of 64-bit floating-point-format strings, and I have to convert them into floating-point numbers. 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.96I 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.
>>>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 8Why did it happened?
I didn't use binascii.a2b_hex or binascii.b2a_hex, beacuse it converts 'A' to '41' or '41' to 'A'. Both are not what I want. Right?
>>>print len('\xC0\x6F\xCA\x5E\x35\x00\x00\x00') 8 >>>print len(myString) 32Now I know why it happened, but I still don't know how to solve the situation.
最满意答案
你可以使用struct.unpack 。 >d是big-endian double; 请参阅help(struct)了解更多信息!
import struct d, = struct.unpack('>d', b'\xc0\x6f\xca\x5e\x35\x00\x00\x00') print(d) # -254.32399988174438如果您的字符串确实是'C06FCA5E35000000' ,则可以使用binascii.a2b_hex将其首先转换为字节。
You can use struct.unpack. >d is a big-endian double; see help(struct) for more!
import struct d, = struct.unpack('>d', b'\xc0\x6f\xca\x5e\x35\x00\x00\x00') print(d) # -254.32399988174438If your string is really 'C06FCA5E35000000', you can convert it first into bytes using binascii.a2b_hex.
更多推荐
发布评论