python - 如何将 uint32_t 转换为无符号字符数组?

标签 python c arrays uint32-t

我正在尝试将转换 uint32_t 值复制到 python 中的 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 中生成的字符串。

即对于 0x240918uint32_t 输入值,我想要 "\000$\t\030"

的输出字符串

我搜索过 SO 但到目前为止无济于事,尤其是这个 -> How to convert integer value to array of four bytes in 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"

也许问题是如何以八进制而不是十六进制打印字节文字?

最佳答案

hmmm a bit different - i'm sure the answer is staring me in the face here but can't see what it is?

30 个八进制即 "\030" 与 18 个十六进制即 "\x18" 相同。它们都代表字节序列中的一个字节,十进制值为 24。

您可以比较 REPL 中的确切值:

bytes((0x00240918 >> i & 0xff) for i in (24,16,8,0)) == b"\000$\t\030"
True

Check the Python documentation on string and byte literals :

  • \ooo 八进制值为 ooo 的字符
  • \xhh 十六进制值为 hh 的字符

这些可以用在字节文字和字符串中(请记住,字符串是 Python 2 中的字节序列)。

我认为 bytes 默认不支持八进制表示(ascii 编解码器始终使用十六进制),但您可以编写自己的代码:

import re
my_b = b'\x00$\t\x18'
print(re.sub(r'\\x([0-9a-f]{2})', lambda a: "\\%03o" % int(a.groups()[0], 16),
  str(my_b)))
# Console result: b'\000$\t\030'

请记住,该字符串包含逐字引号和 b' 前缀,并且它可以接受转义的斜杠作为十六进制序列。如果你真的想要一个好的八进制 __repr__ 最好的方法是创建一个循环并检查不可打印的字符,将它们转换为 3 位八进制并将所有内容连接成一个字符串。

关于python - 如何将 uint32_t 转换为无符号字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56048461/

相关文章:

python - 为什么我收到此 Django 自定义命令错误 : 'datetime.timezone' has no attribute 'now'

c - 快速排序中的交换和比较

javascript - 将值映射到对象数组中

python pygame blit。获取要显示的图像

python - 具有 "depends_on"的属性特征

c++ - 如何在 boost.python 中转换 std::string* ?

arrays - 生成嵌套的 Numpy 数组

php - 如何使用两个插入查询循环复选框中的两个值

python - 找不到 Django 主页的模板

C- 不正确的方法需要纠正