Reputation: 1019
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
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
Reputation: 142206
Another option is:
from binascii import hexlify
>>> hexlify('a1n4')
'61316e34'
Upvotes: 0
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
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