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

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

提交回复
热议问题