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

后端 未结 15 1397
深忆病人
深忆病人 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:20

    Here is the code for one that I made for college. Click Here for a youtube video of the code.! https://www.youtube.com/watch?v=SGTZzJ5H-CE

    __author__ = 'Derek'
    print('Int to binary')
    intStr = input('Give me an int: ')
    myInt = int(intStr)
    binStr = ''
    while myInt > 0:
        binStr = str(myInt % 2) + binStr
        myInt //= 2
    print('The binary of', intStr, 'is', binStr)
    print('\nBinary to int')
    binStr = input('Give me a binary string: ')
    temp = binStr
    newInt = 0
    power = 0
    while len(temp) > 0:   # While the length of the array if greater than zero keep looping through
        bit = int(temp[-1])   # bit is were you temporally store the converted binary number before adding it to the total
        newInt = newInt + bit * 2 ** power  # newInt is the total,  Each time it loops it adds bit to newInt.
        temp = temp[:-1]  # this moves you to the next item in the string.
        power += 1  # adds one to the power each time.
    print("The binary number " + binStr, 'as an integer is', newInt)
    
    0 讨论(0)
  • 2020-12-07 01:21

    Not the pythonic way...but still works:

    def get_binary_list_from_decimal(integer, bits):
        '''Return a list of 0's and 1's representing a decimal type integer.
    
        Keyword arguments:
        integer -- decimal type number.
        bits -- number of bits to represent the integer.
    
        Usage example:
        #Convert 3 to a binary list
        get_binary_list_from_decimal(3, 4)
        #Return will be [0, 0, 1, 1]
        '''
        #Validate bits parameter.
        if 2**bits <= integer:
            raise ValueError("Error: Number of bits is not sufficient to \
                              represent the integer. Increase bits parameter.")
    
        #Initialise binary list
        binary_list = []
        remainder = integer
        for i in range(bits-1, -1, -1):
            #If current bit value is less than or equal to the remainder of 
            #the integer then bit value is 1.
            if 2**i <= remainder:
                binary_list.append(1)
                #Subtract the current bit value from the integer.
                remainder = remainder - 2**i
            else:
                binary_list.append(0)
    
        return binary_list
    

    Example of how to use it:

    get_binary_list_from_decimal(1, 3)
    #Return will be [0, 0, 1]
    
    0 讨论(0)
  • 2020-12-07 01:24

    Just sharing a function that processes an array of ints:

    def to_binary_string(x):
        length = len(bin(max(x))[2:])
    
        for i in x:
            b = bin(i)[2:].zfill(length)
    
            yield [int(n) for n in b]
    

    Test:

    x1 = to_binary_string([1, 2, 3])
    x2 = to_binary_string([1, 2, 3, 4])
    
    print(list(x1)) # [[0, 1], [1, 0], [1, 1]]
    print(list(x2)) # [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0]]
    
    0 讨论(0)
  • 2020-12-07 01:25

    Just for fun - the solution as a recursive one-liner:

    def tobin(x):
        return tobin(x/2) + [x%2] if x > 1 else [x]
    
    0 讨论(0)
  • 2020-12-07 01:29

    You can use numpy package and get very fast solution:

    python -m timeit -s "import numpy as np; x=np.array([8], dtype=np.uint8)" "np.unpackbits(x)"
    1000000 loops, best of 3: 0.65 usec per loop
    
    python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
    100000 loops, best of 3: 3.68 usec per loop
    

    unpackbits handles inputs of uint8 type only, but you can still use np.view:

    python -m timeit -s "import numpy as np; x=np.array([124567], dtype=np.uint64).view(np.uint8)" "np.unpackbits(x)"
    1000000 loops, best of 3: 0.697 usec per loop
    
    0 讨论(0)
  • 2020-12-07 01:29
    def nToKBit(n, K=64):
       output = [0]*K
    
       def loop(n, i):
           if n == 0: 
               return output
           output[-i] = n & 1
           return loop(n >> 1, i+1)
    
       return loop(n, 1)
    
    0 讨论(0)
提交回复
热议问题