Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary numbers of N digits

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

like image 917
singhiskng Avatar asked Aug 31 '14 07:08

singhiskng


2 Answers

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.
like image 172
falsetru Avatar answered Oct 18 '22 04:10

falsetru


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
like image 20
Scorpion_God Avatar answered Oct 18 '22 02:10

Scorpion_God