Om *_*ash -2 python python-2.x python-2.7
我想在python中编写一个以mac地址为参数并将该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
Run Code Online (Sandbox Code Playgroud)
实际上在第3行,我想将macaddress的内容复制到mac我只是想知道我写的正确与否
Byt*_*der 16
它就像这一行一样简单:
mac_int = int(mac_str.translate(None, ":.- "), 16)
Run Code Online (Sandbox Code Playgroud)
这首先删除可能的字节分隔符(" :"," ."," -"或" " 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))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5186 次 |
| 最近记录: |