将64位浮点格式字符串转换为浮点数(Convert 64

编程入门 行业动态 更新时间:2024-10-21 03:51:38
将64位浮点格式字符串转换为浮点数(Convert 64-bits floating-point format string to floating-point number)

我有一堆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.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.

>>>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'. 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.

最满意答案

你可以使用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.32399988174438

If your string is really 'C06FCA5E35000000', you can convert it first into bytes using binascii.a2b_hex.

更多推荐

本文发布于:2023-07-05 06:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034401.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   字符串   转换为   格式   浮点数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!