2

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.

Richard
  • 15,152
  • 31
  • 85
  • 111
  • 5
    Just use `bin()` and [left-pad the result](http://stackoverflow.com/questions/339007/python-nicest-way-to-pad-zeroes-to-string). – Matt Ball Oct 07 '11 at 13:27

2 Answers2

9

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.

agf
  • 171,228
  • 44
  • 289
  • 238
0

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
Balazs Kanyo
  • 183
  • 7