4

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.

4 Answers 4

8

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
Sign up to request clarification or add additional context in comments.

Comments

3
a = 'somestring'
print a[0]        # first byte
print ord(a[1])   # value of second byte

(x for x in a)    # is a iterable generator

Comments

3

You can iterate through a string just as you can any other sequence.

for c in 'Hello':
  print c

Comments

0
mystring = "a1234f"
data = list(mystring)

Data will be a list where each element is a character from the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.