Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a float to bytearray

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?

like image 360
tatatat0 Avatar asked Apr 27 '16 14:04

tatatat0


2 Answers

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']
like image 168
cdarke Avatar answered Sep 21 '22 18:09

cdarke


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.

like image 24
jfs Avatar answered Sep 17 '22 18:09

jfs