将float转换为bytearray

tat*_*at0 7 python python-3.x

所以,我想要做的是将一个浮点数转换为一个bytearray,但我继续接收无输入,并且EXTREME减慢/冻结我的计算机.我的代码是

import struct

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])
value = 5.1 #example value
...
value = bytearray(int(float_to_hex(float(value)), 16)
Run Code Online (Sandbox Code Playgroud)

我在另一篇文章中找到了一个将浮点数转换为十六进制的函数

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])
Run Code Online (Sandbox Code Playgroud)

然后我将它从十六进制转换为int.这有什么问题?我怎么能更好地将它从浮点数转换为bin或bytearray?

cda*_*rke 12

这取决于你想要什么,以及你将要做什么.如果你想要的只是一个bytearray:

import struct

value = 5.1

ba = bytearray(struct.pack("f", value))  
Run Code Online (Sandbox Code Playgroud)

babytearray 在哪里?但是,如果您希望显示十六进制值(我怀疑),那么:

print([ "0x%02x" % b for b in ba ])
Run Code Online (Sandbox Code Playgroud)

编辑:

这给出了(对于值5.1):

['0x33', '0x33', '0xa3', '0x40']
Run Code Online (Sandbox Code Playgroud)

但是,CPython使用C类型double来存储甚至很小的浮动(这有很好的理由),所以:

value = 5.1
ba = bytearray(struct.pack("d", value))   
print([ "0x%02x" % b for b in ba ])
Run Code Online (Sandbox Code Playgroud)

得到:

['0x66', '0x66', '0x66', '0x66', '0x66', '0x66', '0x14', '0x40']
Run Code Online (Sandbox Code Playgroud)

  • 格式化十六进制的格式更好/更快(删除`0x`并将其保留为单个十六进制字符串)将是`struct.pack("f",value).hex()`(需要3.5+但产生`str `for output out)或`binascii.hexlify(struct.pack("f",value))`(适用于任何Python版本,但返回`bytes`对象;需要解码为`ascii`才能得到`str`例如`binascii.hexlify(struct.pack("f",value)).decode('ascii')`).但如果目标只是一个"bytearray",没有格式化,那么是的,你所拥有的是显而易见的方式. (2认同)

jfs*_*jfs 7

我想要的 5.1 的结果是 0x40 a3 33 33 或 64 163 51 51。不是字符串。

要从浮点中获取所需的整数列表:

>>> import struct
>>> list(struct.pack("!f", 5.1))
[64, 163, 51, 51]
Run Code Online (Sandbox Code Playgroud)

或者与类型相同bytearray

>>> bytearray(struct.pack("!f", 5.1))
bytearray(b'@\xa333')
Run Code Online (Sandbox Code Playgroud)

注意:字节串(bytes类型)包含完全相同的字节:

>>> struct.pack("!f", 5.1)
b'@\xa333'
>>> for byte in struct.pack("!f", 5.1):
...    print(byte)
...
64
163
51
51
Run Code Online (Sandbox Code Playgroud)

区别仅在于可变性。list,bytearray是可变序列,而bytestype 表示不可变的字节序列。否则,bytes类型bytearray具有非常相似的 API。