When I am reading individual elements from bytes it is returning a integer value rather than returning the hex code. This I am noticing with Python 3 only (tested in v3.10). Any idea how this can adjusted? Below are the code and output from both Python 2.7 (which works fine) and Python 3.10 (which is converting to integers).
Python 2.7 (works fine)
>>> test = b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> test[0]
'\x00'
>>> test[1]
'\x01'
>>>
Python 3.10 (converting output to integers).
>>> test = b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>>
>>> test[0]
0
>>> test[1]
1
>>>
CodePudding user response:
Python 3 has a bytes
type. When you create a binary string with b'...'
, you create an immutable sequence of bytes. Indexing that sequence returns type int
. A slice of a b-string will be in bytes
form like this:
>>> test[:2]
b'\x00\x01'
Python 2 did not have a bytes
type, and in fact the b
prefix on a string is ignored. '\x00\x01....'
is just a string of non-representable characters in hex-escape syntax. Indexing and slicing that string returns another string (of one or more characters).