Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I produce a hex-escaped string in python that I can use in C++?

Tags:

python

I'm trying to create synthesized unit tests for a library that uses MessagePack. I would like to create hex-escaped binary strings in python that I can embed in C++ sources. I'm creating one like this:

In [6]: umsgpack.packb([0, 0, 'dummy_void_zeroarg', []])
Out[6]: '\x94\x00\x00\xc4\x12dummy_void_zeroarg\x90'

However, it looks like the resulting hex string is almost, but not quite usable in C++:

error: hex escape sequence out of range
        "\x94\x00\x00\xc4\x12dummy_void_zeroarg\x90";
                         ^~~~~

The reason is that the compiler tries to parse \x12d as a single value. Is there a way to transform the above hex string to one in python that does not contain letters (i.e. only \x items)?

like image 943
Tamás Szelei Avatar asked Nov 16 '25 13:11

Tamás Szelei


1 Answers

You'll have to do so manually:

"'{}'".format(''.join(['\\x{:02x}'.format(ord(c)) for c in message]))

Print the result or write it to a file:

>>> print "'{}'".format(''.join(['\\x{:02x}'.format(ord(c)) for c in message]))
'\x94\x00\x00\xc4\x12\x64\x75\x6d\x6d\x79\x5f\x76\x6f\x69\x64\x5f\x7a\x65\x72\x6f\x61\x72\x67\x90'
like image 175
Martijn Pieters Avatar answered Nov 18 '25 03:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!