Patrick
Patrick

Reputation: 1019

Str to hex in Python

I receive on my socket a 4 bytes value that I want to print as hex value. I am trying:

 print "%08x" % (nonce)

However, I get an error message that string can't be converted to hex. Anyone an idea how this could be quickly resolved?

Upvotes: 0

Views: 5091

Answers (5)

E.Z.
E.Z.

Reputation: 6661

If your data can be converted to a string, you could use the str.encode() method:

>>> s = "XYZ"
>>> s.encode('hex')
'58595a'

Upvotes: 0

Jun HU
Jun HU

Reputation: 3314

num = "9999"
print hex(int(num))
#0x270f

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142206

Another option is:

from binascii import hexlify
>>> hexlify('a1n4')
'61316e34'

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318568

You most likely have a string containing the bytes. However, to print them as a number you need well.. a number.

You can easily create the hex string you are looking for like this:

''.join('%02x' % ord(x) for x in nonce)

Demo:

>>> nonce = os.urandom(4)
>>> nonce
'X\x19e\x07'
>>> ''.join('%02x' % ord(x) for x in nonce)
'58196507'

Upvotes: 0

user4815162342
user4815162342

Reputation: 155226

Use the struct module to unpack the octets received from the network into an actual number. The %08x format will work on the number:

import struct
n, = struct.unpack('>I', nonce)
print "%08x" % n

Upvotes: 3

Related Questions