Python 将浮点数转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36893206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting a float to bytearray
提问by tatatat0
So, what I am trying to do is convert a float to a bytearray but I keep on receiving both no input, and EXTREME slowing/freezing of my computer. My code is
所以,我想要做的是将浮点数转换为字节数组,但我一直没有收到任何输入,并且我的计算机非常缓慢/冻结。我的代码是
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)
I found on another article a function to convert floats to hex which is
我在另一篇文章中发现了一个将浮点数转换为十六进制的函数,它是
def float_to_hex(f):
return hex(struct.unpack('<I', struct.pack('<f', f))[0])
and then I converted it from hex to an int. What is the problem with this? How could I better convert it from a float to bin or bytearray?
然后我将它从十六进制转换为整数。这有什么问题?我怎样才能更好地将它从浮点数转换为 bin 或 bytearray?
回答by cdarke
It depends what you want, and what you are going to do with it. If all you want is a bytearray then:
这取决于你想要什么,以及你打算用它做什么。如果你想要的只是一个字节数组,那么:
import struct
value = 5.1
ba = bytearray(struct.pack("f", value))
Where ba
is a bytearray. However, if you wish to display the hex values (which I suspect), then:
ba
字节数组在哪里。但是,如果您希望显示十六进制值(我怀疑),则:
print([ "0x%02x" % b for b in ba ])
EDIT:
编辑:
This gives (for value 5.1):
这给出(对于值 5.1):
['0x33', '0x33', '0xa3', '0x40']
However, CPython uses the C type double
to store even small floats (there are good reasons for that), so:
然而,CPython 使用 C 类型double
来存储甚至小的浮点数(有充分的理由),所以:
value = 5.1
ba = bytearray(struct.pack("d", value))
print([ "0x%02x" % b for b in ba ])
Gives:
给出:
['0x66', '0x66', '0x66', '0x66', '0x66', '0x66', '0x14', '0x40']
回答by jfs
The result I would want from 5.1 is 0x40 a3 33 33 or 64 163 51 51. Not as a string.
我想要 5.1 的结果是 0x40 a3 33 33 或 64 163 51 51。不是字符串。
To get the desired list of integers from the float:
要从浮点数中获取所需的整数列表:
>>> import struct
>>> list(struct.pack("!f", 5.1))
[64, 163, 51, 51]
Or the same as a bytearray
type:
或与bytearray
类型相同:
>>> bytearray(struct.pack("!f", 5.1))
bytearray(b'@\xa333')
Note: the bytestring (bytes
type) contains exactly the same bytes:
注意:字节串(bytes
类型)包含完全相同的字节:
>>> struct.pack("!f", 5.1)
b'@\xa333'
>>> for byte in struct.pack("!f", 5.1):
... print(byte)
...
64
163
51
51
The difference is only in mutability. list
, bytearray
are mutable sequences while bytes
type represents an immutable sequence of bytes. Otherwise, bytes
and bytearray
types have a very similar API.
区别仅在于可变性。list
,bytearray
是可变序列,而bytes
type 表示不可变的字节序列。否则,bytes
和bytearray
类型具有非常相似的 API。