2 回答

TA貢獻1921條經驗 獲得超9個贊
類型和具有您需要的方法。intbytes
請注意,我從類中調用,但它可以從實例對象調用:from_bytesintint
>>> a = 2**32-1
>>> a.to_bytes(4, 'little')
b'\xff\xff\xff\xff'
>>> b = a.to_bytes(4, 'little')
>>> c = int.from_bytes(b, 'little')
>>> c
4294967295
>>> a
4294967295
>>>

TA貢獻1880條經驗 獲得超4個贊
給定提到的間隔,您正在談論無符號int。
[Python 3.Docs]:結構 - 將字符串解釋為打包的二進制數據可以正常工作(好吧,在 sizeof(int) == 4 的平臺(編譯器)
上)。
由于對于絕大多數環境,上述情況是正確的,因此您可以安全地使用它(除非您確信代碼將在一個陌生的平臺上運行,其中用于構建Python的編譯器是不同的)。
>>> import struct
>>>
>>> bo = "<" # byte order: little endian
>>>
>>> ui_max = 0xFFFFFFFF
>>>
>>> ui_max
4294967295
>>> buf = struct.pack(bo + "I", ui_max)
>>> buf, len(buf)
(b'\xff\xff\xff\xff', 4)
>>>
>>> ui0 = struct.unpack(bo + "I", buf)[0]
>>> ui0
4294967295
>>>
>>> i0 = struct.unpack(bo + "i", buf)[0] # signed int
>>> i0
-1
>>> struct.pack(bo + "I", 0)
b'\x00\x00\x00\x00'
>>>
>>> struct.pack(bo + "I", ui_max + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: argument out of range
>>>
>>> struct.unpack(bo + "I", b"1234")
(875770417,)
>>>
>>> struct.unpack(bo + "I", b"123") # 3 bytes buffer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: unpack requires a buffer of 4 bytes
>>>
>>> struct.unpack(bo + "I", b"12345") # 5 bytes buffer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: unpack requires a buffer of 4 bytes
相關(遠程): [SO]:C 的最大值和最小值來自 Python 的整數。
[蟒蛇 3.文檔]: ctypes - 蟒蛇變體的外來函數庫:
>>> # Continuation of previous snippet
>>> import ctypes as ct
>>>
>>> ct_ui_max = ct.c_uint32(ui_max)
>>>
>>> ct_ui_max
c_ulong(4294967295)
>>>
>>> buf = bytes(ct_ui_max)
>>> buf, len(buf)
(b'\xff\xff\xff\xff', 4)
>>>
>>> ct.c_uint32(ui_max + 1)
c_ulong(0)
>>>
>>> ct.c_uint32.from_buffer_copy(buf)
c_ulong(4294967295)
>>> ct.c_uint32.from_buffer_copy(buf + b"\x00")
c_ulong(4294967295)
>>> ct.c_uint32.from_buffer_copy(b"\x00" + buf) # 0xFFFFFF00 (little endian)
c_ulong(4294967040)
>>>
>>> ct.c_uint32.from_buffer_copy(buf[:-1])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Buffer size too small (3 instead of at least 4 bytes)
注意:@progmatico的答案更簡單,更直接,因為它不涉及內置模塊以外的任何模塊([Python 3.Docs]:內置類型 - 整數類型的附加方法)。作為旁注,可以使用系統字節順序。
添加回答
舉報