问题
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.
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/7687928/convert-dec-number-to-6-bit-binary-number