Python Forum
Conversion needed from bytearray to Floating point
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Conversion needed from bytearray to Floating point
#1
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
Reply
#2
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'>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Value error when converting hex value to bytearray shubhamjainj 7 10,468 Mar-20-2023, 05:30 PM
Last Post: Skaperen
  appending to a bytearray Skaperen 21 14,088 Mar-19-2023, 11:05 PM
Last Post: Skaperen
  Split Bytearray into separate Files by Hex delimter lastyle 5 2,616 Mar-09-2023, 07:49 AM
Last Post: bowlofred
  Save multiple Parts of Bytearray to File ? lastyle 1 934 Dec-10-2022, 08:09 AM
Last Post: Gribouillis
  bytearray object - why converting to ascii? Chepilo 2 1,606 Nov-21-2022, 07:25 PM
Last Post: Chepilo
  floating point not increasing properly rakeshpe43 4 2,382 Apr-30-2020, 05:37 AM
Last Post: rakeshpe43
  Bytearray substitution Vismuto 1 2,593 Apr-14-2020, 09:18 AM
Last Post: TomToad
  connecting the first point to the last point Matplotlib omar_mohsen 0 4,574 Jan-15-2020, 01:23 PM
Last Post: omar_mohsen
  Complex floating issue arshad 2 11,815 Nov-05-2019, 03:26 PM
Last Post: arshad
  floating point arithmetic exDeveloper 2 2,097 Sep-25-2019, 04:33 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020