Python Forum

Full Version: Conversion needed from bytearray to Floating point
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello All,

I am stuck in very strange situation. My python code is talking to some third party device and getting data which is in bytearray format. I need this final value in real/float format
import ctypes
import struct
import math
client = c.Client()
client.connect('192.168.27.11', 0, 3)

def get_db_row(db, start, size):
    data = client.db_read(db, start, size)
    return (data)
    client.disconnect()
    client.destroy()
.
It gives me following output when input is
Output:
bytearray(b'B\xc8\x00\x00')
which is equivalent to (42H C8H 00H 00H) and Float value 100.0

I have tried many ways Wall Wall but I am not able to convert this byte array to output value 100.0
Can anyone please help?

Thanks
Using struct should do it.
>>> import struct
>>> 
>>> b = bytearray(b'B\xc8\x00\x00')
>>> b
bytearray(b'B\xc8\x00\x00')

>>> f = struct.unpack('>f', b)
>>> f
(100.0,)
>>> f[0]
100.0
>>> type(f[0])
<class 'float'>