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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:22:33  来源:igfitidea点击:

python 2.7 equivalent of built-in method int.from_bytes

pythonpython-2.7compatibility

提问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 imeans signed 32 bit int

>表示 big-endiani表示有符号的 32 位 int

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

另见:https: //docs.python.org/2/library/struct.html

回答by SanketDG

Use the structmodule to unpack your bytes into integers.

使用该struct模块将您的字节解包为整数。

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

回答by Dan

> import binascii

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

0xABCDEF