简体   繁体   中英

how to convert mac address to decimal in python

I want to write a function in python that take mac address as argument and convert that mac address to decimal form.please provide solution supported in python2

I have written a code

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

actually in 3rd line where i want to copy content of macaddress to mac i just wanted to know that i have written correct way or not

It is as simple as this line:

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

This first removes the possible byte separator characters (" : ", " . ", " - " or " " 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 eg str.format to convert the integer into a hexadecimal string and then just insert the colons back into it:

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

the following function will do the trick

import re

def mac_to_int(mac):
    res = re.match('^((?:(?:[0-9a-f]{2}):){5}[0-9a-f]{2})$', mac.lower())
    if res is None:
        raise ValueError('invalid mac address')
    return int(res.group(0).replace(':', ''), 16)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM