Converting binary numbers to decimal and vice-versa in the most straightforward way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Guyon Morée
# http://gumuz.looze.net/
def Binary2Decimal(bin_num):
""" Return the decimal representation of bin_num
This actually uses the built-in int() function,
but is wrapped in a function for consistency """
return int(bin_num, 2)
def Decimal2Binary(dec_num):
""" Return the binary representation of dec_num """
if dec_num == 0: return '0'
return (Decimal2Binary(dec_num >> 1) + str(dec_num % 2))
|
The simplest thing that could possibly work, I believe.
>>> Decimal2Binary(2005)
'011111010101'
>>> Binary2Decimal('011111010101')
2005
Tags: algorithms
problems. 1) does not properly handle negative numbers or floats
2) Leaves a leading '0' on the string it returns
To fix these, you could do:
still has problem. The modified version can not handle 0 correctly.
Not '0' as expected. Is there a better solution?
sure.
Opportunity to use divmod().
control leading zeros.
a bit faster. binary operators should be fastest when it comes to dealing with binary values