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?
heximplies you want hexadecimal text, not the raw bytes, and in that case, you wouldn't want abytearrayat all (which is a binary data type), you'd wantstr(the text type in Python 3). - ShadowRangerfloator Cdoublerepresentation? - ShadowRangerfloattype is actually based on the Cdoubletype, not the Cfloattype (which is typically half the precision ofdouble), so you might want format coded, notf. As I mentioned in another comment, on 3.5,struct.pack("f", value).hex()should get you the hexadecimal text you want. - ShadowRanger