python 2.7 equivalent of built-in method int.from_bytes

Posted on

Question :

python 2.7 equivalent of built-in method int.from_bytes

I’m trying to make my project python2.7 and 3 compatible and python 3 has the built in method int.from_bytes. Does the equivalent exist in python 2.7 or rather what would be the best way to make this code 2.7 and 3 compatible?

>>> int.from_bytes(b"f483", byteorder="big")

Answer #1:

You can treat it as an encoding (Python 2 specific):

>>> int('f483'.encode('hex'), 16)

Or in Python 2 and Python 3:

>>> int(codecs.encode(b'f483', 'hex'), 16)

The advantage is the string is not limited to a specific size assumption. The disadvantage is it is unsigned.

Answered By: dawg

Answer #2:



> means big-endian and i means signed 32 bit int

see also:

Answered By: Joran Beasley

Answer #3:

Use the struct module to unpack your bytes into integers.

import struct
>>> struct.unpack("<L", "yxccxa6xbb")[0]
Answered By: SanketDG

Answer #4:

> import binascii

> barray = bytearray([0xAB, 0xCD, 0xEF])
> n = int(binascii.hexlify(barray), 16)
> print("0x%02X" % n)

Answered By: Dan

Leave a Reply

Your email address will not be published. Required fields are marked *