[英]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. 我正在尝试使我的项目python2.7和3兼容,而python 3具有内置方法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?
是否存在python 2.7中的等价物,或者说这个代码2.7和3兼容的最佳方法是什么?
>>> int.from_bytes(b"f483", byteorder="big")
1714698291
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.
缺点是它是未签名的。
struct.unpack(">i","f483")[0]
maybe? 也许?
>
means big-endian and i
means signed 32 bit int >
表示big-endian, i
意思是签名32位int
see also: https://docs.python.org/2/library/struct.html 另见: https : //docs.python.org/2/library/struct.html
> import binascii
> barray = bytearray([0xAB, 0xCD, 0xEF])
> n = int(binascii.hexlify(barray), 16)
> print("0x%02X" % n)
0xABCDEF
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.