Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading bytes from Python String

Tags:

python

string

hex

I have hex data in a string. I need to be able parse the string byte by byte, but through reading the docs, the only way to get data bytewise is through the f.read(1) function.

How do I parse a string of hex characters, either into a list, or into an array, or some structure where I can access byte by byte.

like image 710
lheezy Avatar asked Dec 10 '22 12:12

lheezy


1 Answers

It sounds like what you might really want (Python 2.x) is:

from binascii import unhexlify
mystring = "a1234f"
print map(ord,unhexlify(mystring))

[161, 35, 79]

This converts each pair of hex characters into its integer representation.

In Python 3.x, you can do:

>>> list(unhexlify(mystring))
[161, 35, 79]

But since the result of unhexlify is a byte string, you can also just access the elements:

>>> L = unhexlify(string)
>>> L
b'\xa1#O'
>>> L[0]
161
>>> L[1]
35

There is also the Python 3 bytes.fromhex() function:

>>> for b in bytes.fromhex(mystring):
...  print(b)
...
161
35
79
like image 60
Mark Tolonen Avatar answered Dec 22 '22 00:12

Mark Tolonen