Search code examples
pythonarrayspython-3.xtype-conversionbyte

How to convert independent bytes to bytearray?


Iam receiving single bytes via serial and I know, that every 4 of them are a float. F.e. I receive b'\x3c' and b'\xff' and I want it to be b'\x3c\xff'. What is the best way to convert it?


Solution

  • You can use join() as you do with strings.

    byte_1 = b'\x3c'
    byte_2 = b'\xff'
    
    joined_bytes = b''.join([byte_1, byte_2]) #b'\x3c\xff'
    

    You can use it along the struct module to obtain your decoded float, be aware it returns a tuple even if it has only one element inside.

    import struct
    
    byte_1 = b'\x3c'
    byte_2 = b'\xff'
    byte_3 = b'\x20'
    byte_4 = b'\xff'
    
    joined_bytes = b''.join([byte_1, byte_2, byte_3, byte_4])
    
    result = struct.unpack('f', joined_bytes)
    print(result[0])