Converting binary to decimal integer output

前端 未结 9 2358
暗喜
暗喜 2021-02-13 16:58

I need to convert a binary input into a decimal integer. I know how to go from a decimal to a binary:

n = int(raw_input(\'enter a number: \'))
print \'{0:b}\'.fo         


        
相关标签:
9条回答
  • 2021-02-13 17:57

    I started working on this problem a long time ago, trying to write my own binary to decimal converter function. I don't actually know how to convert decimal to binary though! I just revisited it today and figured it out and this is what I came up with. I'm not sure if this is what you need, but here it is:

    def __degree(number):
        power = 1
    
        while number % (10**power) != number:
            power += 1
    
        return power
    
    def __getDigits(number):
        digits = []
        degree = __degree(number)
    
        for x in range(0, degree):
            digits.append(int(((number % (10**(degree-x))) - (number % (10**(degree-x-1)))) / (10**(degree-x-1))))
        return digits
    
    def binaryToDecimal(number):
        list = __getDigits(number)
        decimalValue = 0
        for x in range(0, len(list)):
            if (list[x] is 1):
                decimalValue += 2**(len(list) - x - 1)
        return decimalValue
    

    Again, I'm still learning Python just on my own, hopefully this helps. The first function determines how many digits there are, the second function actually figures out they are and returns them in a list, and the third function is the only one you actually need to call, and it calculates the decimal value. If your teacher actually wanted you to write your own converter, this works, I haven't tested it with every number, but it seems to work perfectly! I'm sure you'll all find the bugs for me! So anyway, I just called it like:

    binaryNum = int(input("Enter a binary number: "))
    
    print(binaryToDecimal(binaryNum))
    

    This prints out the correct result. Cheers!

    0 讨论(0)
  • 2021-02-13 18:00

    This is the full thing

    binary = input('enter a number: ')
    decimal = 0
    for digit in binary:
    decimal= decimal*2 + int(digit)
    
    print (decimal)
    
    0 讨论(0)
  • 2021-02-13 18:00

    Try this solution:

    def binary_int_to_decimal(binary):
        n = 0
        for d in binary:
            n = n * 2 + d
    
        return n
    
    0 讨论(0)
提交回复
热议问题