python中mac地址的十进制转换

2024-06-16 09:53:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用python编写一个函数,用mac address作为参数,并将mac地址转换成十进制形式。请提供python2支持的解决方案

我写了一个代码

def mac_to_int(macaddress): 
   i=0  
   mac=list(macaddress)
   mac_int=0;   
 for i in range(len(macaddress)):
   mac_int=mac_int<<8
   mac_int+=mac[i]

return mac_int

实际上,在第三行,我想把macaddress的内容复制到mac,我只想知道我写得是否正确


Tags: to函数代码for参数addressmac地址
1条回答
网友
1楼 · 发布于 2024-06-16 09:53:04

就这么简单:

mac_int = int(mac_str.translate(None, ":.- "), 16)

这首先删除可能的字节分隔符(“:”、“.”、“-”或“" but you can add more if you want) and then parses the string as integer with base 16 (hexadecimal).


As it has been asked for, the other way round could use e.g. str.format”以将整数转换为十六进制字符串,然后将冒号重新插入其中:

mac_hex = "{:012x}".format(mac_int)
mac_str = ":".join(mac_hex[i:i+2] for i in range(0, len(mac_hex), 2))

相关问题 更多 >