我正在尝试在Python中复制将uint32_t
值转换为unsigned char
数组的过程(我已经在C中完成了此操作)。
这是我的现有C函数:
unsigned char *uint32_to_char_array(const uint32_t n)
{
unsigned char *a;
a = wrap_calloc(4, sizeof(unsigned char));
a[0] = (n >> 24) & 0xff; /* high-order (leftmost) byte: bits 24-31 */
a[1] = (n >> 16) & 0xff; /* next byte, counting from left: bits 16-23 */
a[2] = (n >> 8) & 0xff; /* next byte, bits 8-15 */
a[3] = n & 0xff; /* low-order byte: bits 0-7 */
return a;
}
如果我在gdb中执行以下操作:
(gdb) p uint32_to_char_array(0x00240918)[0]@4 = "\000$\t\030"
我正在尝试在Python中生成该字符串。
即,对于输入值为0x240918
的uint32_t
,我希望得到一个输出字符串"\000$\t\030"
我已经搜索了SO,但迄今为止没有结果,特别是这个 -> 如何将整数值转换为Python中的四个字节数组,但没有一个答案似乎能产生上述的输入/输出组合
我正在使用2.7,但如果需要,可以使用> 3.0。
更新:
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 0x240918.to_bytes(4, "big")
b'\x00$\t\x18'
嗯,有些不同——我确定答案就在我的面前,但我看不到它是什么?
那么我能看到:
>>> b"\000$\t\030"
b'\x00$\t\x18'
但是如何实现相反的效果呢?即:
>>> b'\x00$\t\x18'
b"\000$\t\030"
也许问题在于如何以八进制而不是十六进制打印字节文字?
to_bytes
方法可以回答你提出的问题:在Python 3.7中,0x240918.to_bytes(4, "big") == b"\000$\t\030"
返回True
。另外,struct.pack('>I', 0x240918)
也可以实现相同的功能。 - Mark Dickinson(0x00240918 >> i & 0xff) for i in (24,16,8,0)
生成的bytes
等于b"\000$\t\030"
,这是正确的。 - Filip Dimitrovskib'\x00$\t\x18'
和b"\000$\t\030"
是同一字符串的不同表示形式。 - Mark Dickinson