Noob questions about Python
Michele Simionato
michele.simionato at gmail.com
Thu Oct 18 02:05:08 EDT 2007
On Oct 17, 5:58 pm, Ixiaus <parnel... at comcast.net> wrote:
> def bin2dec(val):
> li = list(val)
> li.reverse()
> res = [int(li[x])*2**x for x in range(len(li))]
> print sum(res)
>
> It basically does the same thing int(string, 2) does.
>
> Thank you for the responses!
BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)
def baseN(number, N=2):
"""
>>> baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0
b = []
while number:
b.append(str(number % N))
number /= N
return ''.join(reversed(b))
Michele Simionato
More information about the Python-list
mailing list