蟒蛇。打印6字节字符串中的mac地址

时间:2011-02-10 16:20:43

标签: python printing tcp

我有6字节字符串的mac地址。你会如何以“人类”可读格式打印它?

由于

6 个答案:

答案 0 :(得分:9)

import struct
"%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",your_variable_with_mac)

答案 1 :(得分:8)

无需使用struct

def prettify(mac_string):
    return ':'.join('%02x' % ord(b) for b in mac_string)

虽然mac_stringbytearray(或Python 3中的bytes),但考虑到数据的性质,这是一个比字符串更自然的选择,那么你也赢了'需要ord功能。

使用示例:

>>> prettify(b'5e\x21\x00r3')
'35:65:21:00:72:33'

答案 2 :(得分:3)

尝试,

for b in addr:
    print("%02x:" % (b))

其中addr是你的字节数组。

答案 3 :(得分:0)

s = b'\ x04NZ \ xdf \ x7f \ xab'

1) 导入结构 ssid_2 =“%02x:%02x:%02x:%02x:%02x:%02x”%struct.unpack(“ BBBBBB”,s)

2) ':'。join(f in {x:02x}'for s in x)

但是1)比2)快

答案 4 :(得分:0)

Python 3.8 及更高版本中,您只能使用bytes.hex

b'\x85n:\xfaGk'.hex(":") // -> '85:6e:3a:fa:47:6b'

答案 5 :(得分:-1)

通常的十六进制格式是不是人类可读的? (see this表示将字节转换为十六进制的方法)

de:ad:be:ef:ca:fe

顺便提一下,这是大多数软件中显示MAC地址的方式(只是Windows使用破折号而不是冒号)。

相关问题