Home > Mobile >  extending 2 bit bytearray to 4 bit
extending 2 bit bytearray to 4 bit

Time:01-10

I'm trying to decode some CAN messages into readable int's. At the moment I'm getting byte arrays with values like this bytearray(b'%\x19')
What I'm trying to do next is to get a float of the byte array with this method
return unpack_from('>f', data, 0)[0]
my problem is that im getting a error like struct.error: unpack_from requires a buffer of at least 4 bytes for unpacking 4 bytes at offset 0 (actual buffer size is 2)

What is the best way to get the right buffer size? I know that 2bits can be converted into a float by using "e" instead of "f" but the values I'm getting are wrong.
I'm using the same method to get the values trough serial connection so I know it is possible.

CodePudding user response:

You can do something like this, you could expand this to support more decimals.

from struct import iter_unpack

data = bytearray(b'%\x19')
my_temp_iter = iter_unpack('>b', data) # you could name this my_temp to not pollute the namespace
my_temp = next(my_temp_iter)[0]   next(my_temp_iter)[0] / 100
print(my_temp) # prints 37.25

Alternitavely, if you know you have 2 bytes

my_temp = data[0]   data[1] / 100
print(my_temp) # prints 37.25
  •  Tags:  
  • Related