Binary numbers of N digits

10,512

Solution 1

Remove the line that pad 0s.

n = 6
for i in xrange(16):
    b = bin(i)[2:]
    l = len(b)
    #b = str(0) * (n - l) + b  # <--------
    print b

If you mean padding number without string oeprator, use str.format with b type format:

n = 6
for i in xrange(16):
    print '{:0{}b}'.format(i, n)
    # OR  print '{:06b}'.format(i)

    # OR  print '{:b}'.format(i)  if you want no leading 0s.

Solution 2

If you're asking for a different method:

n = 6
for i in xrange(16):
    b = bin(i)[2:].zfill(n)
    print b

str.zfill(n) pads the string with zeros on the left so that it is at least of length n.


If you just don't want the leading zeros:

for i in xrange(16):
    b = bin(i)[2:]
    print b

Solution 3

You can use list comprehension and bit conversions together like this: n = range

def binary_list(n):
    return ['{:0{}b}'.format(i, n) for i in range(n*n-1)]

print(binary_list(3)) -->
['000', '001', '010', '011', '100', '101', '110', '111']

or if you want to store each number in its own index do:

def binary_list(n):
    return [[int(j) for j in '{:0{}b}'.format(i, n)] for i in range(n*n-1)]

print(binary_list(3))--->
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]

Share:
10,512
singhiskng
Author by

singhiskng

I just love programming ,gaming ,learning new facts in physics ,maths and technology.

Updated on June 13, 2022

Comments

  • singhiskng
    singhiskng almost 2 years

    for generating binary numbers in n digit
    i did this to get upto 16 binary numbers.

    n = 6                       # for 6 digits
    for i in xrange(16):
        b = bin(i)[2:]
        l = len(b)
        b = str(0) * (n - l) + b
        print b
    

    it results like this

    000000
    000001
    000010
    000011
    000100
    000101
    000110
    000111
    001000
    001001
    001010
    001011
    001100
    001101
    001110
    001111
    

    but what i want is to get these values without adding a series of 0s in prefix.
    can anyone help me for this.
    thanks