Search code examples
pythonpython-2.7base-conversion

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

Solution

  • 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))