簡體   English   中英

python 2.7相當於內置方法int.from_bytes

[英]python 2.7 equivalent of built-in method int.from_bytes

我正在嘗試使我的項目python2.7和3兼容,而python 3具有內置方法int.from_bytes。 是否存在python 2.7中的等價物,或者說這個代碼2.7和3兼容的最佳方法是什么?

>>> int.from_bytes(b"f483", byteorder="big")
1714698291

您可以將其視為編碼(特定於Python 2):

>>> int('f483'.encode('hex'), 16)
1714698291

或者在Python 2和Python 3中:

>>> int(codecs.encode(b'f483', 'hex'), 16)
1714698291

優點是字符串不限於特定大小的假設。 缺點是它是未簽名的。

struct.unpack(">i","f483")[0]

也許?

>表示big-endian, i意思是簽名32位int

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

使用struct模塊將字節解壓縮為整數。

import struct
>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L
> 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM