Reputation: 15882
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:
etc... with the largest dec number allowed being 63.
Upvotes: 2
Views: 3695
Reputation: 183
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
Upvotes: 0
Reputation: 176850
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.
Upvotes: 9