Skip to content

Instantly share code, notes, and snippets.

@nlm
Created May 12, 2017 09:31
Show Gist options
  • Save nlm/9ec20c78c4881cf23ed132ae59570340 to your computer and use it in GitHub Desktop.
Save nlm/9ec20c78c4881cf23ed132ae59570340 to your computer and use it in GitHub Desktop.
mac address <=> integer conversions in python
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)
def int_to_mac(macint):
if type(macint) != int:
raise ValueError('invalid integer')
return ':'.join(['{}{}'.format(a, b)
for a, b
in zip(*[iter('{:012x}'.format(macint))]*2)])
@BruceMty
Copy link

BruceMty commented Dec 6, 2021

Without any error checking:

import re

def mac_to_int(mac):
    return int(mac.replace(":", ""), 16)

def int_to_mac(macint):
    return  ":".join(re.findall("..", "%012x"%macint))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment