python 2.7 相当于内置方法 int.from_bytes
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30402743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python 2.7 equivalent of built-in method int.from_bytes
提问by Fabian Barkhau
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
采纳答案by dawg
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.
优点是字符串不限于特定大小的假设。缺点是未签名。
回答by Joran Beasley
struct.unpack(">i","f483")[0]
maybe?
也许?
>
means big-endian and i
means signed 32 bit int
>
表示 big-endiani
表示有符号的 32 位 int
回答by SanketDG
回答by Dan
> import binascii
> barray = bytearray([0xAB, 0xCD, 0xEF])
> n = int(binascii.hexlify(barray), 16)
> print("0x%02X" % n)
0xABCDEF