I have a byte string similar to the following.
foo = b"\x00\xff"
I want to convert foo
each hex value into an integer. I can use the following in Python 3.
In [0]: foo[0]
Out[0]: 0
In [1]: foo[1]
Out[1]: 255
Python 2 requires an ord()
call.
In [0]: ord(foo[0])
Out[0]: 0
In [1]: ord(foo[1])
Out[1]: 255
Is there a nice way to write this in code that has to work across both Python 2 and 3? The six
package has a six.byte2int()
function but that doesn't work because it only looks at the first byte and six.byte2int(foo[0]
fails on Python 3 because foo[0]
is an integer in Python 3.
Is there a better option than a if six.PY2
branch?
You have three options:
Use a bytearray()
:
ba = bytearray(foo)
ba[0]
Use the struct
module to unpack your bytes into integers:
import struct
struct.unpack('{}B'.format(len(foo)), foo)
Use the array
module to unpack your bytes into integers, in a sequence:
import array
array.array('B', foo)
Demo (Python 2.7):
>>> import struct, array
>>> foo = b"\x00\xff"
>>> list(bytearray(foo))
[0, 255]
>>> struct.unpack('{}B'.format(len(foo)), foo)
(0, 255)
>>> array.array('B', foo)
array('B', [0, 255])
Demo (Python 3.4):
>>> import struct, array
>>> foo = b"\x00\xff"
>>> list(bytearray(foo))
[0, 255]
>>> struct.unpack('{}B'.format(len(foo)), foo)
(0, 255)
>>> array.array('B', foo)
array('B', [0, 255])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With