Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5

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

It outputs:
But I would like to have:
Where is the problem?

Best regards,
No problem - HEX values that correspond to ASCII characters are shown like those characters
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
In [12]: import array In [13]: array.array('B', (0xd0, 0x13, 0x74)).tobytes() Out[13]: b'\xd0\x13t'
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Try the following construction:
for x in barray:
To paraphrase: 'Throw out your dead' code. Forward to 1:00
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
Another method could be str-formatting:
ba = bytearray(b'\xd0\x13t')
hexstr = ''.join(format(integer, 'x') for integer in ba) 
For Python 3.6 fans with format string interpolation:
ba = bytearray(b'\xd0\x13t')
hexstr = ''.join(f'{integer:x}' for integer in ba) 
My code examples are always for Python 3.x.
All humans together. We don't need politicians!

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Simple Byte Question malonn 3 91 Aug-29-2018, 12:14 AM
Last Post: malonn
  4 byte hex byte swap from binary file medievil 7 542 May-08-2018, 08:16 AM
Last Post: killerrex
  python charmap codec can't decode byte X in position Y character maps to < undefined> owais 9 9,633 Apr-28-2018, 10:52 PM
Last Post: abadawi
  I have an array, how can I search a seperate file for the contents of my array? Mr_Keystrokes 0 298 Mar-13-2018, 02:25 PM
Last Post: Mr_Keystrokes
  get the content of the byte as string ricardons 5 342 Mar-02-2018, 02:41 PM
Last Post: ricardons
  lists, strings, and byte strings Skaperen 2 268 Mar-02-2018, 02:12 AM
Last Post: Skaperen
  converting array of things to byte stream to send bigjoey 2 251 Feb-27-2018, 12:56 PM
Last Post: bigjoey
  byte string Skaperen 5 458 Feb-04-2018, 08:58 AM
Last Post: Gribouillis
  byte string in python2 Skaperen 4 613 Nov-23-2017, 03:13 AM
Last Post: Skaperen
  Convert list of integers to bit-mapped byte eccles 10 1,123 Oct-25-2017, 07:35 PM
Last Post: eccles

Forum Jump:

Users browsing this thread: 1 Guest(s)