Byte-Array - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Byte-Array (/thread-10918.html) |
Byte-Array - okmog - Jun-13-2018 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 RE: Byte-Array - volcano63 - Jun-13-2018 No problem - HEX values that correspond to ASCII characters are shown like those characters
I would have used array to build bytestring - initializing values one-by-one does not look very Pythonic
RE: Byte-Array - ljmetzger - Jun-13-2018 Try the following construction: for x in barray: print(hex(x))Lewis RE: Byte-Array - DeaD_EyE - Jun-13-2018 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) |