简体   繁体   中英

convert dec number to 6 bit binary number

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM