Created
September 8, 2016 06:34
-
-
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.
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
#!/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), )) | |
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