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

6 comments

Bill Mill 16 years, 6 months ago  # | flag

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 <= 0: return ''
    return D(n>>1) + str(n%2)
Qiangning Hong 16 years, 6 months ago  # | flag

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

>>> D(0)
''

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

Bill Mill 16 years, 6 months ago  # | flag

sure.

def E(n):
    '''undefined on negative numbers, non-integers'''
    s = ''
    if n < 0: return ''
    if n == 0: return '0'
    while n > 0:
        s = str(n%2) + s
        n = n >> 1
    return s
Raymond Hettinger 16 years, 5 months ago  # | flag

Opportunity to use divmod().

def Decimal2Binary(dec_num):
    """ Return the binary representation of dec_num """
    if dec_num == 0: return '0'
    head, tail = divmod(dec_num, 2)
    return Decimal2Binary(head) + str(tail)
Darrell Gallion 16 years, 4 months ago  # | flag

control leading zeros.

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 15 years, 11 months ago  # | flag

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

def bit_is_set(n, num): return (1 << n) & num != 0

def int_to_bin(num):
    out, n = '', 0
    while (1 << n) <= num:
        out += ((1 << n) & 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)
Python recipes (4591)
Guyon Morée's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks