Skip to content

Instantly share code, notes, and snippets.

@naftulikay
Created September 8, 2016 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naftulikay/47c27d909f21fa3d91fa10a320484722 to your computer and use it in GitHub Desktop.
Save naftulikay/47c27d909f21fa3d91fa10a320484722 to your computer and use it in GitHub Desktop.
Get 32 most or least significant bits of a MAC address - format a MAC address as a 32 bit integer.
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
from math import floor, log
def binary_macaddress(macaddress):
"""Convert a mac address into a 48-bit integer."""
binary = 0
for octet in map(lambda a: int(a, 16), macaddress.split(':')):
binary = binary << 8
binary = binary | octet
return binary
def get_min_bits(numb):
"""
Returns the minimum amount of bits necessary to represent an arbitrary
number.
"""
return int(floor(log(numb) / log(2)))
def get_32bit_mac_left(macaddress):
"""Get the left-most 32 bits of a MAC address in constant time, baby."""
b = binary_macaddress(macaddress)
# shift right by 16 bits no matter what
return b >> 16
def get_32bit_mac_right(macaddress):
"""Get the right-most 32 bits of a MAC address, still constant time."""
b = binary_macaddress(macaddress)
# by anding it against the max 32-bit integer, we take the 32 right-most
# bits
return b & (2**32 - 1)
def binfmt(v):
return bin(v)[2:]
def zfillfmt_l(v, size=48):
s = binfmt(v)
return ((size - len(s)) * '0') + s
def zfillfmt_r(v, size=48):
s = binfmt(v)
return s + ((size - (len(s) + 1)) * '0')
def test(macaddress):
b = binary_macaddress(macaddress)
l = get_32bit_mac_left(macaddress)
r = get_32bit_mac_right(macaddress)
print("Test Case: {}".format(macaddress))
print("--------------------------------------------------------")
print("Binary: %048s" % (zfillfmt_l(b), ))
print("Right: %48s" % (zfillfmt_r(r, 32), ))
print("Left: %-48s" % (zfillfmt_l(l, 32), ))
print
test("ff:ff:ff:ff:ff:ff")
test("01:23:45:67:89:ab")
test("00:00:00:00:00:00")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment