tehmaze/ipcalc

binary representation is quite circonvoluted?

Closed this issue · 2 comments

jul commented

https://github.com/tehmaze/ipcalc/blob/master/src/ipcalc.py#L190

The code is quite complicated, but if understand the API, it only converts self.ip (a long) to its binary representation as a string.
so maybe : this could be sufficient?

def bin(self): return '{0:b}'.format(self.ip)

Well, the string formatting you suggest is available since Python 2.6. Also the bin() function exists since 2.6. Do you have a suggestion that is compatible with Python 2.5 (or 2.4 even)?

jul commented

Maybe ?

def int_to_bit(an_int):
while an_int!=0:
yield int(an_int&1 )
an_int>>=1

def bit_vector(an_int):
a=[ o for o in int_to_bit(an_int) ]
return a

def bin(an_int):
a=bit_vector(an_int)
a.reverse()
return "".join([ str(j) for j in a ])

I am sure there is an obfuscated way of doing it taking as much CPU,
but this one is readable :)