Question

I am looking to convert a dec number to a 6 bit binary number.. bin() works fine but omits leading zeros which are important.

for example:

  • 0 = 000000
  • 1 = 000001
  • 2 = 000010

etc... with the largest dec number allowed being 63.

Was it helpful?

Solution

Either what Matt said in the comment (bin(63)[2:].zfill(6)), or use format strings in Python 2.6+:

'{0:06b}'.format(63)

You can omit the first zero in Python 2.7+ as you can implicitly number groups.

OTHER TIPS

Or just:

n2=[2**x for x in xrange(0, 7)]
n2.reverse()

def getx(x):
    ret = ''
    for z in n2:
        if x >= z:
            x -= z
            ret += '1'
        else:
            ret += '0'

    return ret
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top