Convert an integer to binary without using the built-in bin function

后端 未结 15 1398
深忆病人
深忆病人 2020-12-07 01:14

This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l

相关标签:
15条回答
  • 2020-12-07 01:32

    Not really the most efficient but at least it provides a simple conceptual way of understanding it...

    1) Floor divide all the numbers by two repeatedly until you reach 1

    2) Going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.

    Here's the literal implementation of that:

    def intToBin(n):
        nums = [n]
        while n > 1:
            n = n // 2
            nums.append(n)
    
        bits = []
        for i in nums:
            bits.append(str(0 if i%2 == 0 else 1))
        bits.reverse()
        print ''.join(bits)
    

    Here's a version that better utilizes memory:

    def intToBin(n):
        bits = []
    
        bits.append(str(0 if n%2 == 0 else 1))
        while n > 1:
            n = n // 2
            bits.append(str(0 if n%2 == 0 else 1))
    
        bits.reverse()
        return ''.join(bits)
    
    0 讨论(0)
  • 2020-12-07 01:33

    may I propose this:

    def tobin(x,s):
        return [(x>>k)&1 for k in range(0,s)]
    

    it is probably the fastest way and it seems pretty clear to me. bin way is too slow when performance matters.

    cheers

    0 讨论(0)
  • 2020-12-07 01:33

    Convert integer to list of bits with a fixed length :

    [int(x) for x in list('{0:0{width}b}'.format(8, width=5))]
    
    0 讨论(0)
提交回复
热议问题