Sam Roberts
Sam Roberts

Reputation: 399

How do I get the output from a hex string to print in hex?

How do I get the output from this hex string to print in hex?

It should be printing to bytes on every line like

31c0
5068
etc

Here's the code:

$ cat hex.py 
#!/usr/bin/python

hexstr = ("\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80")

x=bytearray(hexstr)

for i in xrange(0,len(x),2):
  print format(x[i:i+2]).decode('hex')

This is the error I get:

$ python  hex.py
Traceback (most recent call last):
  File "hex.py", line 8, in <module>
    print format(x[i:i+2]).decode('hex')
  File "/usr/lib/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

Upvotes: 1

Views: 1007

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121864

You don't have a hex string. You have a regular Python string defined with \xhh hex escape codes.

If you wanted to display these bytes as hex, all you have to do is encode them with the hex codec:

>>> hexstr = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80"
>>> hexstr.encode('hex')
'31c050682f2f7368682f62696e89e35089e25389e1b00bcd80'

An alternative method is to use the binascii.hexlify() function for the same result.

If you need each byte on a separate line, just loop over the string and encode individual characters (bytes):

>>> for c in hexstr:
...     print c.encode('hex')
... 
31
c0
50
68
2f
2f
73
68
68
2f
62
69
6e
89
e3
50
89
e2
53
89
e1
b0
0b
cd
80

Upvotes: 2

Related Questions