3

I have MAC address that I want to send to dpkt as raw data. dpkt package expect me to pass the data as hex stings. So, assuming I have the following mac address: '00:de:34:ef:2e:f4', written as: '00de34ef2ef4' and I want to encode in to something like '\x00\xdeU\xef.\xf4' and the backward translation will provide the original data.

On Python 2, I found couple of ways to do that using encode('hex') and decode('hex'). However this solution isn't working for Python 3.

I'm haveng some trouble finding a code-snippet to support that on both versions.

I'd appriciate help on this.

Thanks

cyber101
  • 899
  • 1
  • 9
  • 19

2 Answers2

8

binascii module works on both Python 2 and 3:

>>> import binascii
>>> binascii.unhexlify('00de34ef2ef4') # to raw binary
b'\x00\xde4\xef.\xf4'
>>> binascii.hexlify(_) # and back to hex
b'00de34ef2ef4'
>>> _.decode('ascii') # as str in Python 3
'00de34ef2ef4'
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • Both solutions did the trick, thanks! I've chosen this one simply because I used `binascii` for other methods in my code. – cyber101 Sep 10 '15 at 07:39
2

On python3 encoding between arbitrary codecs must be done using the codecs module:

>>> import codecs
>>> codecs.decode(b'00de34ef2ef4', 'hex')
b'\x00\xde4\xef.\xf4'
>>> codecs.encode(b'\x00\xde4\xef.\xf4', 'hex')
b'00de34ef2ef4'

This will only work with bytes, not with str (unicode) objects. It will also work in python2.7, where str is bytes and the b-prefix does nothing.

mata
  • 67,110
  • 10
  • 163
  • 162