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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With