Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Bit manipulation with comments solution in Clear category for IP Network: Route Summarization by lezeroq
def checkio(data):
# functions to convert string ip representation to 32bit integer and vice versa
str2ip = lambda ip: sum(int(n)*(256**p) for p, n in enumerate(reversed(ip.split('.'))))
ip2str = lambda ip: '.'.join(str((ip & (1 << i) - 1) >> (i - 8)) for i in range(32, 0, -8))
ips = [str2ip(i) for i in data] # convert string ip representaion to ints
# min and max ip are enought to find out common left bits for all ips in data
ip1 = min(ips) # min ip from data
ip2 = max(ips) # max ip from data
diff = ip1 ^ ip2 # calculate bits which is different for min and max ips
# next cycle is to calculate number of significant bits in 'diff' and then
# 'subnet' = 32 - 'number of significant bits'
subnet = 32
mask = (1 << 32) - 1 # 0b 11111111 11111111 11111111 11111111
while diff: # while diff has set bits
diff >>= 1 # shift all bits to right by one place
mask <<= 1 # shift all bits to left by one place and add 0 bit to the end
subnet -= 1 # decrease subnet number
network = ip1 & mask # put mask on any of ips
return '%s/%d' % (ip2str(network), subnet)
March 9, 2016
Comments: