21

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")
1714698291
Fabian Barkhau
  • 1,349
  • 2
  • 12
  • 31

4 Answers4

27

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

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

Or in Python 2 and Python 3:

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

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

dawg
  • 98,345
  • 23
  • 131
  • 206
12
struct.unpack(">i","f483")[0]

maybe?

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

see also: https://docs.python.org/2/library/struct.html

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
7

Use the struct module to unpack your bytes into integers.

import struct
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L
SanketDG
  • 550
  • 5
  • 12
  • that just unpacks them into bytes ... he wants them all as 1 32 bit integer ... maybe bigger ... but you are right that stuct is the module to use :) – Joran Beasley May 22 '15 at 18:11
  • 1
    I didn't realize he needed the actual integer values, but yeah, fixed. – SanketDG May 22 '15 at 19:31
1
> import binascii

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

0xABCDEF
Dan
  • 2,452
  • 20
  • 45