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

后端 未结 15 1551
深忆病人
深忆病人 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)
    

提交回复
热议问题