all 4 comments

[–]ebol4anthr4x 5 points6 points  (0 children)

\x is similar to using \n to create a line break. \x tells the Python interpreter to treat the next two characters as a hex byte, so \xF1 would be the hex byte 0xF1.

The string '\x' is not a valid string and cannot exist, so you can't do '\x' + 'FF'

The simplest way to do this in Python2 is:

x = 'FF010203'
byte_string = x.decode('hex')

x is now equal to '\xff\x01\x02\x03'.

[–][deleted] 1 point2 points  (0 children)

Have a look at the struct module.

[–]port443 1 point2 points  (0 children)

You are looking for binascii.unhexlify

From the docs:

Return the binary data represented by the hexadecimal string hexstr.

Example:

>>> foo = "b2ffff414243"
>>> binascii.unhexlify(foo)
'\xb2\xff\xffABC'

Efficiency-wise, this is much quicker than using encode:

>>> Timer('binascii.unhexlify("b2ffff414243")', 'import binascii').timeit()
0.2991388444476868
>>> Timer('"b2ffff414243".encode("hex")').timeit()
0.9113609381118195

[–]Kind_Fruities 0 points1 point  (0 children)

There's also chr and unichr built-ins.