从 mac 地址转换为十六进制字符串,反之亦然 - python 2 和 3

Convert from mac address to hex string and vice versa - both python 2 and 3

我有 MAC 个地址,我想将其作为原始数据发送到 dpkt。 dpkt 包希望我将数据作为十六进制字符串传递。 因此,假设我有以下 mac 地址:'00:de:34:ef:2e:f4',写为:'00de34ef2ef4' 并且我想编码成类似 '\x00\xdeU\xef.\xf4' 的内容,反向翻译将提供原始内容数据。

在 Python 2 上,我找到了几种使用 encode('hex') 和解码 ('hex') 的方法。 但是,此解决方案不适用于 Python 3.

我很难找到一个代码片段来支持这两个版本。

我希望得到帮助。

谢谢

On python3 任意编解码器之间的编码必须使用 codecs 模块完成:

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

这仅适用于 bytes,不适用于 str (unicode) 对象。它也适用于 python2.7,其中 strbytesb 前缀什么都不做。

binascii module 适用于 Python 2 和 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'