简体   繁体   English

如何在python字符串中表示十六进制值?

[英]How do I represent a hex value in a python string?

I have some code in C that expects char buffer that looks like this: 我在C中有一些代码需要char缓冲区,如下所示:

 char buf[ 64 ];
    buf[0] = 0x01;
    buf[1] = 0x11;
    buf[2] = 0x61;
    buf[3] = 0x08;
    buf[4] = 0x01;

I am trying to create this buffer in Python, and pass the pointer to the C code. 我试图在Python中创建此缓冲区,并将指针传递给C代码。 I created buf as follows, 我创建了如下buf,

buf = create_string_buffer('0x01 0x11 0x61 0x08 0x01', 64)

but when I pass the pointer to my C code, it looks like the C code is reading the ASCII code for 01, not a hex literal. 但是当我将指针传递给我的C代码时,看起来C代码正在读取01的ASCII代码,而不是十六进制文字。

How do I fix this? 我该如何解决?

In Python hex literals are escaped by \\x 在Python中,十六进制文字由\\x转义

so in your case the string to pass into your c function would be written as 所以在你的情况下,传递给你的c函数的字符串将被写为

'\x01\x11\x61\x08\x01'

There is a table here in the python docs listing the escape sequences that python understands. 有一个表在这里的python文档列出了蟒蛇理解转义序列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM