Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert between int array or tuple vs bytes correctly

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,)

Questions:

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?

like image 591
henry783333 Avatar asked Oct 13 '25 00:10

henry783333


1 Answers

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)
like image 166
Patrick Haugh Avatar answered Oct 14 '25 17:10

Patrick Haugh