Welcome, guest | Sign In | My Account | Store | Cart

Converting binary numbers to decimal and vice-versa in the most straightforward way.

Python, 15 lines
 ``` 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
``````

Bill Mill 17 years, 9 months ago

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:

``````def D(n):
'''undefined on negative numbers, non-integers'''
if n &lt;= 0: return ''
return D(n&gt;&gt;1) + str(n%2)
``````
Qiangning Hong 17 years, 9 months ago

still has problem. The modified version can not handle 0 correctly.

``````>>> D(0)
''
``````

Not '0' as expected. Is there a better solution?

Bill Mill 17 years, 9 months ago

sure.

``````def E(n):
'''undefined on negative numbers, non-integers'''
s = ''
if n &lt; 0: return ''
if n == 0: return '0'
while n > 0:
s = str(n%2) + s
n = n >> 1
return s
``````
Raymond Hettinger 17 years, 9 months ago

Opportunity to use divmod().

``````def Decimal2Binary(dec_num):
""" Return the binary representation of dec_num """
if dec_num == 0: return '0'
``````
Darrell Gallion 17 years, 8 months ago

``````def Decimal2BinaryBits(dec_num, bits):
res = Decimal2Binary(dec_num)[:bits].zfill(bits)
return res

print Decimal2BinaryBits(0x1234, 16)
>0001001000110100
print Decimal2Binary(0x1234)
>01001000110100
``````
Jürgen Urner 17 years, 3 months ago

a bit faster. binary operators should be fastest when it comes to dealing with binary values

``````def bit_is_set(n, num): return (1 &lt;&lt; n) &amp; num != 0

def int_to_bin(num):
out, n = '', 0
while (1 &lt;&lt; n) &lt;= num:
out += ((1 &lt;&lt; n) &amp; num != 0)  and '1' or '0'  # bit_is_set()
n += 1
return out and out[-1::-1] or '0'
``````
 Created by Guyon Morée on Wed, 8 Jun 2005 (PSF)

### Required Modules

• (none specified)