Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interpret spaces in python byte arrays

Tags:

python

I am receiving some data from a third party and stumbled over a curious feature of the byte array output:

Some byte arrays I receive have spaces in the string which is printed to console, and I do not know how to interpet these.

a = b'\x14 \x00'
b = b'\x14\x00'

print(len(a), ':', a[0], a[1], a[2])
print(len(b), ':', b[0], b[1])

results in the output

3 : 20 32 0
2 : 20 0

Where does the 32 (which is '\x20' in hex) come from?
ASCII space is 32, but why is this interpreted as such?

like image 869
SchillerFalke2 Avatar asked Aug 02 '26 03:08

SchillerFalke2


1 Answers

32 is the decimal value for the string " " (a space). In Python, a bytes object is an iterable of bytes 0-255, which can be represented by \x14 for 0x14, or ASCII characters like a, b, or c. Or a combination of the two, as you've seen in your example.

list(b'\x01\b02')   # [1, 2]
list(b'ab')         # [97, 98] (decimal values for 'a' and 'b')
list(b'\x12ab\x44') # [18, 97, 98, 68]
like image 189
acurtis Avatar answered Aug 04 '26 16:08

acurtis