Reading bytes from Python String
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
a = 'somestring'
print a[0] # first byte
print ord(a[1]) # value of second byte
(x for x in a) # is a iterable generator
You can iterate through a string just as you can any other sequence.
for c in 'Hello':
print c
mystring = "a1234f"
data = list(mystring)
Data will be a list where each element is a character from the string.
精彩评论