Created
May 12, 2017 09:31
-
-
Save nlm/9ec20c78c4881cf23ed132ae59570340 to your computer and use it in GitHub Desktop.
mac address <=> integer conversions in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without any error checking: