Python Forum

Full Version: Byte-Array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I would like to assign hex values to a byte array, however for some values python assign letters to the array instead hex values.

For example:
length = bytes(3)
barray = bytearray(length)

# construct example array
barray[0] = 0xd0
barray[1] = 0x13
barray[2] = 0x74

print(barray) 
It outputs:
bytearray(b'\xd0\x13t')
But I would like to have:
bytearray(b'\xd0\x13\x74')
Where is the problem?

Best regards,
Olli
No problem - HEX values that correspond to ASCII characters are shown like those characters
Output:
In [7]: chr(0x74) Out[7]: 't'

I would have used array to build bytestring - initializing values one-by-one does not look very Pythonic
Output:
In [12]: import array In [13]: array.array('B', (0xd0, 0x13, 0x74)).tobytes() Out[13]: b'\xd0\x13t'
Try the following construction:
for x in barray:
    print(hex(x)) 
Lewis
I guess there is no one right way how you can solve this task.

You can work with binascii.hexlify
from binascii import hexlify


ba = bytearray(b'\xd0\x13t')
hexstr = hexlify(ba).decode() # hexlify returns bytes
print(hexstr)
Another method could be str-formatting:
ba = bytearray(b'\xd0\x13t')
hexstr = ''.join(format(integer, 'x') for integer in ba) 
print(hexstr)
For Python 3.6 fans with format string interpolation:
ba = bytearray(b'\xd0\x13t')
hexstr = ''.join(f'{integer:x}' for integer in ba) 
print(hexstr)