python - Convert hex into string literal: replacing 0x with \x

I need to send a command comprised of hex values, like so: "\x06\x01\x00\x44". The string is then encoded into binary, using the built in .encode() function, and sent off into Telnet.

For reasons I do not understand, this does not work if the string is formatted using the other hex formatting (0x instead of \x): "0x060x010x000x44", so I am trying to only use \x.

I need to insert a value into the command before converting it, but I do not know how to take an integer input and convert it into a hexadecimal string literal.

I can do this:

input_int = 100
hex_value = hex(input_int)

But that just leaves me with hex_value = '0x64', which is not the same as '\x64'.

Is there a shortcut I am missing, or some way to just turn the int straight into a hex literal string?

(I am using Python 2.7, by the way.)

1 Answer

  1. Elvis- Reply


    Turns out chr() is what I was looking for. It turns the integer value into the ASCII character with the proper value.

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>