Reading Bytes from a Python String

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

How to parse a string of hexadecimal characters either in a list, or in an array, or in some structure where I can access byte by byte.

+3
source share
4 answers
mystring = "a1234f"
data = list(mystring)

The data will be a list in which each item is a character from a string.

0
source

It looks like you really want (Python 2.x):

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

[161, 35, 79]

.

Python 3.x :

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

unhexlify , :

>>> L = unhexlify(string)
>>> L
b'\xa1#O'
>>> L[0]
161
>>> L[1]
35
+7
a = 'somestring'
print a[0]        # first byte
print ord(a[1])   # value of second byte

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

You can iterate over a string just like any other sequence.

for c in 'Hello':
  print c
+3
source

Source: https://habr.com/ru/post/1777126/


All Articles