22

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
1
  • 1
    If you're specifically looking for a cross-version solution then you should make this clear in the title. Commented May 22, 2015 at 17:45

5 Answers 5

29

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.

Sign up to request clarification or add additional context in comments.

4 Comments

hah I like this solution ... alot ... its one I would not have thought of :) it has the added advantage of not having to know anything about the input
Yours is better really cause it should work in Python 2 and 3. Thanks tho
What would be the reverse of this? I'd like to retrieve the original byte string from the integer
What about ord(b'\x11')?
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

2 Comments

it won't work for anything bigger than int32 of course. any hints?
When the bytes is less than 4 this won't work, when it would have worked for int.from_bytes()
6

Use the struct module to unpack your bytes into integers.

import struct
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L

2 Comments

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 :)
I didn't realize he needed the actual integer values, but yeah, fixed.
1
> import binascii

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

0xABCDEF

Comments

0

I was looking for a 2.7 version that works with signed integers from 8 chars wide hex strings, so also negative numbers and came up with this using struct:

>>> import struct

>>> n = 'ffffffd6'
>>> struct.unpack(">l", n.decode('hex'))[0]
-42

>>> n4 = 'ffd6'
>>> struct.unpack(">h", n4.decode('hex'))[0]
-42

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.