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?
我正在尝试使我的项目python2.7和3兼容,而python 3具有内置方法int.from_bytes。是否存在python 2.7中的等价物,或者说这个代码2.7和3兼容的最佳方法是什么?
>>> int.from_bytes(b"f483", byteorder="big")
1714698291
3 个解决方案
#1
18
You can treat it as an encoding (Python 2 specific):
您可以将其视为编码(特定于Python 2):
>>> int('f483'.encode('hex'), 16)
1714698291
Or in Python 2 and Python 3:
或者在Python 2和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.
优点是字符串不限于特定大小的假设。缺点是它是未签名的。
#2
5
struct.unpack(">i","f483")[0]
maybe?
也许?
>
means big-endian and i
means signed 32 bit int
>表示big-endian,我的意思是签名32位int
see also: https://docs.python.org/2/library/struct.html
另见:https://docs.python.org/2/library/struct.html
#3
3
Use the struct
module to unpack your bytes into integers.
使用struct模块将字节解压缩为整数。
import struct
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L
#1
18
You can treat it as an encoding (Python 2 specific):
您可以将其视为编码(特定于Python 2):
>>> int('f483'.encode('hex'), 16)
1714698291
Or in Python 2 and Python 3:
或者在Python 2和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.
优点是字符串不限于特定大小的假设。缺点是它是未签名的。
#2
5
struct.unpack(">i","f483")[0]
maybe?
也许?
>
means big-endian and i
means signed 32 bit int
>表示big-endian,我的意思是签名32位int
see also: https://docs.python.org/2/library/struct.html
另见:https://docs.python.org/2/library/struct.html
#3
3
Use the struct
module to unpack your bytes into integers.
使用struct模块将字节解压缩为整数。
import struct
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L