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'
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'
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])
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With