亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python 打包/解包編號指定字節數

python 打包/解包編號指定字節數

泛舟湖上清波郎朗 2022-09-27 10:00:41
我正在嘗試將Python中的int數字(> = 0 > <2 ^ 32)轉換為4字節無符號int表示并返回。據我所知,struct.pack中給出的文檔大小是標準的,但不能保證大小。我如何確保我得到4個字節?我發現使用ctypes的一種方式:byte_repr=bytes(ctypes.c_uint32(data))這是最悍褻的嗎?回去的路是什么(對于這個或任何其他解決方案)?
查看完整描述

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

>>>


查看完整回答
反對 回復 2022-09-27
?
慕村225694

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]:內置類型 - 整數類型的附加方法)。作為旁注,可以使用系統字節順序。


查看完整回答
反對 回復 2022-09-27
  • 2 回答
  • 0 關注
  • 162 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號