Conversion needed from bytearray to Floating point - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Conversion needed from bytearray to Floating point (/thread-9969.html) |
Conversion needed from bytearray to Floating point - braveYug - May-07-2018 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 which is equivalent to (42H C8H 00H 00H) and Float value 100.0I have tried many ways but I am not able to convert this byte array to output value 100.0 Can anyone please help? Thanks RE: Conversion needed from bytearray to Floating point - snippsat - May-07-2018 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'> |