Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python 3: string to hex, hex to format

Tags:

python-3.x

hex

Question: I need to convert a string into hex and then format the hex output.

tmp = b"test"
test = binascii.hexlify(tmp)
print(test) 

output: b'74657374'


I want to format this hex output to look like this: 74:65:73:74

I have hit a road block and not sure where to start. I did think of converting the output to a string again and then trying to format it but there must be an easier way.

Any help would be appreciated, thanks.

==========

OS: Windows 7

tmp = "test"
hex = str(binascii.hexlify(tmp), 'ascii')
print(hex)

formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
print(formatted_hex

[Error] Traceback (most recent call last): File "C:\pkg\scripts\Hex\hex.py", line 24, in hex = str(binascii.hexlify(tmp), 'ascii') TypeError: 'str' does not support the buffer interface

This code only works when using tmp = b'test' I need be able use tmp = importString in fashion as I'm passing another value to it from a file order for my snippet to work. Any thoughts?

like image 499
onxx Avatar asked Aug 20 '12 04:08

onxx


Video Answer


2 Answers

hex = str(binascii.hexlify(tmp), 'ascii')
formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))

This makes use of the step argument to range() which specifies that instead of giving every integer in the range, it should only give every 2nd integer (for step=2).


>>> tmp = "test"
>>> import binascii
>>> hex = str(binascii.hexlify(tmp), 'ascii')
>>> formatted_hex = ':'.join(hex[i:i+2] for i in range(0, len(hex), 2))
>>> formatted_hex
'74:65:73:74'
like image 161
Amber Avatar answered Oct 24 '22 17:10

Amber


>>> from itertools import izip_longest, islice
>>> t = b"test".encode('hex')
>>> ':'.join(x[0]+x[1] for x in izip_longest(islice(t,0,None,2),islice(t,1,None,2)))
'74:65:73:74'
like image 23
Burhan Khalid Avatar answered Oct 24 '22 18:10

Burhan Khalid