Converting a float to bytearray
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:
print([ "0x%02x" % b for b in ba ])
EDIT:
This gives (for value 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:
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']
The result I would want from 5.1 is 0x40 a3 33 33 or 64 163 51 51. Not as a string.
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(struct.pack("!f", 5.1))
bytearray(b'@\xa333')
Note: the bytestring (bytes
type) contains exactly the same 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.