Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print Hex With Spaces Between

I'm trying to print my hex out in another way...

First I'm converting this (bytestring is the name of the variable):

b'\xff\x00\xff\xff\xff'

to hex,

print(bytestring.hex())

which outputs:

ff00ffffff

but I've been trying for a while to get it to output this:

ff 00 ff ff ff

but no luck.

Any suggestions? Cheers!


Update:

stringdata = f.read(5)
print(stringdata)
#b'\xff\x00\xff\xff\xff'

readHex = " ".join(["{:02x}".format(x) for x in stringdata.hex()])
# ValueError: Unknown format code 'x' for object of type 'str'
like image 706
chxevsny Avatar asked Aug 22 '18 20:08

chxevsny


3 Answers

In Python 3.8+, hex function has an optional argument splitter.

>>> print(b'\xff\x00\xff\xff\xff'.hex(' '))
'ff 00 ff ff ff'

And you can split the hex string with any character you want.

>>> print(b'\xff\x00\xff\xff\xff'.hex(':'))
'ff:00:ff:ff:ff'
like image 120
PX.Liu Avatar answered Sep 24 '22 23:09

PX.Liu


just convert your array of bytes to hex strings, and join the result with space:

>>> d=b'\xff\x00\xff\xff\xff'
>>> " ".join(["{:02x}".format(x) for x in d])
'ff 00 ff ff ff'

note that " ".join("{:02x}".format(x) for x in d) would also work, but forcing the list creation is faster as explained here: Joining strings. Generator or list comprehension?

In python 2, bytes is str so you have to use ord to get character code

>>> " ".join(["{:02x}".format(ord(x)) for x in d])
like image 29
Jean-François Fabre Avatar answered Sep 24 '22 23:09

Jean-François Fabre


Seems like the community does not agree that this is a dupe, so I'll post my comment as an answer.

You can convert to a string:

bytestring = str(b'\xff\x00\xff\xff\xff').encode('hex')
print(bytestring)
#ff00ffffff

Then iterate over it in chunks of 2, and join the chunks with a space:

print(" ".join([bytestring[i:i+2] for i in range(0, len(bytestring), 2)]))
#'ff 00 ff ff ff'
like image 38
pault Avatar answered Sep 22 '22 23:09

pault