Binary numbers

Steve Purcell stephen_purcell at yahoo.com
Tue Feb 6 18:05:19 CET 2001


sampe99 at my-deja.com wrote:
> Does anyone know an easy way to get a list of binary numbers within a
> certain range in python? E.g for
> n=1 [0],[1]
> n=2 [0,0],[0,1],[1,0],[1,1]
> n=3 [0,0,0],[0,0,1] a.s.o
> 
> I need this for n<=18...

How about:

def binary(num):
    digits = [] 
    power = 0  
    while 2 ** power <= num:
        if 2 ** power & num:
            digits.append(1)
        else:
            digits.append(0)
        power = power + 1
    digits.reverse()     
    return digits   

for n in range(18):
    print n, '=', binary(n)


The output is as follows:

0 = []
1 = [1]
2 = [1, 0]
3 = [1, 1]
4 = [1, 0, 0]
5 = [1, 0, 1]
6 = [1, 1, 0]


The 'reverse' means that the list output has the most significant digits first,
which seems to be what you want.

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Available for consulting and training.
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list