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.

asked Nov 26, 2010 at 21:58

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
answered Nov 27, 2010 at 1:03
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
answered Nov 26, 2010 at 22:03

Comments

3

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

for c in 'Hello':
 print c
answered Nov 26, 2010 at 22:04

Comments

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

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

answered Nov 26, 2010 at 22:02

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.