Bot
Bot

Reputation: 59

How would i count up in binary with leading zeros?

So I want to count up in binary but keep the leading zeros in example to count to 6 it'd look like this:

0000

0001

0010

0011

0100

0101

0110

I have this code but it only goes up to a certain amount specified by repeat=4 and i need it to go until it finds a specific number.

for i in itertools.product([0,1],repeat=4):
x += 1
print i
if binNum == i:
    print "Found after ", x, "attempts"
    break

Upvotes: 0

Views: 1367

Answers (3)

Joe
Joe

Reputation: 7141

A more pythonic way is

for k in range(7): #range's stop is not included

    print('{:04b}'.format(k))

This uses Python's string formatting language (https://docs.python.org/3/library/string.html#format-specification-mini-language)

To print higher numbers in blocks of four use something like

for k in range(20): #range's stop is not included

    # https://docs.python.org/3/library/string.html#format-specification-mini-language

    if len('{:b}'.format(k)) > 4:
        print(k, '{:08b}'.format(k))
    else:
        print('{:04b}'.format(k))

You could even dynamically adjust the formatting term '{:08b}' using the string formatting language itself and the equation y = 2^x to work for any integer:

from math import ceil

for k in range(300):

    print(k, '{{:0{:.0f}b}}'.format(ceil((len(bin(k))-2)/4)*4).format(k))

Upvotes: 2

Ani Menon
Ani Menon

Reputation: 28277

Without leading zeros

n=5   # End number
i=0   # index var
while i < n:
    print format(i, "04b") 
    i+=1

The above example would display from 0 to 5. And 04b gives you 4 characters as the result (with leading zeros).

Output:

0000
0001
0010
0011
0100

With leading zeros

while( i <= n ):
    len_bin = len(bin(i)[2:])
    if(len_bin%4 != 0):
        lead = 4 - len_bin % 4
    else:
        lead = 0
    print format(i, "0"+str(lead+len_bin)+"b")
    i+=1

The above code would go from i to n and display the binary with leading zeros.

Upvotes: 2

Bot
Bot

Reputation: 59

Nevermind guys, I found the answer!

I simply put it in a while loop like this:

while found == 0:
repeatTimes += 1
for i in itertools.product([0,1],repeat=repeatTimes):
    x += 1
    print i
    if binNum == i:
        found = 1
        pos = x
        break

Upvotes: 1

Related Questions