Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 and 3 compatible method to convert bytes to integer

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?

like image 981
Ayrx Avatar asked Dec 26 '22 03:12

Ayrx


1 Answers

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])
like image 62
Martijn Pieters Avatar answered Mar 24 '23 01:03

Martijn Pieters