如何将MAC号转换为MAC字符串?

时间:2012-01-26 15:49:35

标签: python

我想将MAC地址00163e2fbab7(存储为字符串)转换为字符串表示形式00:16:3e:2f:ba:b7。 最简单的方法是什么?

6 个答案:

答案 0 :(得分:24)

使用完全迂回的方法来利用现有的函数,该函数一次分组两个十六进制字符:

>>> ':'.join(s.encode('hex') for s in '00163e2fbab7'.decode('hex'))
'00:16:3e:2f:ba:b7'

针对Python 3进行了更新:

>>> ':'.join(format(s, '02x') for s in bytes.fromhex('00163e2fbab7'))
'00:16:3e:2f:ba:b7'

答案 1 :(得分:11)

使用grouper idiom zip(*[iter(s)]*n)

In [32]: addr = '00163e2fbab7'

In [33]: ':'.join(''.join(pair) for pair in zip(*[iter(addr)]*2))
Out[33]: '00:16:3e:2f:ba:b7'

也可能,(事实上,更快一点):

In [36]: ':'.join(addr[i:i+2] for i in range(0,len(addr),2))
Out[36]: '00:16:3e:2f:ba:b7'

答案 2 :(得分:5)

如果你想要用冒号加入一个字符串s,这应该可以解决问题。

':'.join([s[i]+s[i+1] for i in range(0,12,2)])

答案 3 :(得分:4)

如果你沉迷于正则表达式,你可以尝试这种unpythonic方法:

>>> import re
>>> s = '00163e2fbab7'
>>> ':'.join(re.findall('..', s))
'00:16:3e:2f:ba:b7'

答案 4 :(得分:0)

<强>&GT;适用于python 3

ap_mac = b'\xfe\xdc\xba\xab\xcd\xef'
decoded_mac = hexlify(ap_mac).decode('ascii')
formatted_mac = re.sub(r'(.{2})(?!$)', r'\1:', decoded_mac)

答案 5 :(得分:0)

我修改了以上乔什·李的答案,以始终生成有效的MAC地址:

def to_mac(addr: int, sep=':'):
    return sep.join('{:02x}'.format(s) for s in bytes.fromhex('{:012x}'.format(addr)))

一些示例/测试:

print(to_mac(0x1))
print(to_mac(0x12))
print(to_mac(0x123))
print(to_mac(0x1234))
print(to_mac(0x12345))
print(to_mac(0x123456))
print(to_mac(0x1234567))
print(to_mac(0x12345678))
print(to_mac(0x123456789))
print(to_mac(0x123456789A))
print(to_mac(0x123456789AB))
print(to_mac(0x123456789ABC, sep='-').upper())

00:00:00:00:00:01
00:00:00:00:00:12
00:00:00:00:01:23
00:00:00:00:12:34
00:00:00:01:23:45
00:00:00:12:34:56
00:00:01:23:45:67
00:00:12:34:56:78
00:01:23:45:67:89
00:12:34:56:78:9a
01:23:45:67:89:ab
12-34-56-78-9A-BC