我正在尝试将Python中的int数(当然>> = 0 && <2 ^ 32)转换为4字节无符号int表示形式并返回。
据我所知,文档中struct.pack
中给出的大小是标准大小,但不能保证大小。.如何确保我得到4个字节?
我发现使用ctypes的一种方法:
struct.pack
这是最pythonic的吗?以及返回的方式(针对此解决方案或其他解决方案)是什么?
类型byte_repr=bytes(ctypes.c_uint32(data))
和int
具有所需的方法。
请注意,我正在从类bytes
调用from_bytes
,但可以从int
实例对象调用它:
int
鉴于上述间隔,您正在谈论unsigned int s。 >>> 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
>>>
正常工作(很好,在[Python 3.Docs]: struct - Interpret strings as packed binary data的平台(编译器)上)。由于在绝大多数环境中上述都是正确的,所以您可以安全地使用它(除非您确信代码将在异国平台上运行,在该平台上用于构建Python的编译器是不同的)。
sizeof(int) == 4
相关(远程):>>> 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
。