user1431282
user1431282

Reputation: 6845

Creating \x Single Char Hex Values in Python

How do you dynamically create single char hex values?

For instance, I tried

a = "ff"
"\x{0}".format(a)

and

a = "ff"
"\x" + a

I ultimately was looking for something like

\xff

However, neither of the combinations above appear to work.

Additionally, I was originally using chr to obtain single char hex representations of integers but I noticed that chr(63) would return ? (as that is its ascii representation).

Is there another function aside from chr that will return chr(63) as \x_ _ where _ _ is its single char hex representation? In other words, a function that only produces single char hex representations.

Upvotes: 1

Views: 1843

Answers (2)

zhangxaochen
zhangxaochen

Reputation: 34027

Try str.decode with 'hex' encoding:

In [204]: a.decode('hex')
Out[204]: '\xff'

Besides, chr returns a single-char string, you don't need to worry about the output of this string:

In [219]: c = chr(31)

In [220]: c
Out[220]: '\x1f'

In [221]: print c #invisible printout


In [222]: 

Upvotes: 2

thefourtheye
thefourtheye

Reputation: 239573

When you say \x{0}, Python escapes x and thinks that the next two characters will be hexa-decimal characters, but they are actually not. Refer the table here.

\xhh  Character with hex value hh (4,5)

4 . Unlike in Standard C, exactly two hex digits are required.

5 . In a string literal, hexadecimal and octal escapes denote the byte with the given value; it is not necessary that the byte encodes a character in the source character set. In a Unicode literal, these escapes denote a Unicode character with the given value.

So, you have to escape \ in \x, like this

print "\\x{0}".format(a)
# \xff

Upvotes: 4

Related Questions