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:

 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. I created buf as follows,

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.

How do I fix this?

1 Answer

In Python hex literals are escaped by \x

so in your case the string to pass into your c function would be written as

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

There is a table here in the python docs listing the escape sequences that python understands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest