Hi I have these codes to convert between int arrays and bytes type variables:
def BYTES_INTARRAY(x):
data_ints = struct.unpack('<' + 'B'*len(x), x)
return data_ints
def INTARRAY_BYTES(x):
data_bytes = struct.pack('<' + 'B'*len(x), *x)
return data_bytes
It seems to work well for bytes that are longer than 1 but when there is only 1 byte it gives a weird result.
For example:
print( INTARRAY_BYTES([255,25]) )
Returns: b'\xff\x19'
Then fed back:
print( BYTES_INTARRAY(b'\xff\x19') )
Returns:
(255, 25)
But if there is only 1 byte:
print( INTARRAY_BYTES([255]) )
Returns: b'\xff'
And fed back:
print( BYTES_INTARRAY(b'\xff') )
Returns: (255,)
1) What the hell is that ,
after the 255. I don't understand the syntax of putting and empty comma there after a number.
2) This code was for python 2.x, is there are more efficient way to do this for python 3.x?
bytes
can be created directly from iterables of integers:
bytes([255, 25])
# b'\xff\x19'
and iterating over bytes
yields integers
tuple(b'\xff\x19')
# (255, 25)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With