Converting binary to decimal integer output

前端 未结 9 2343
暗喜
暗喜 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-13 17:52

    You can use int and set the base to 2 (for binary):

    >>> binary = raw_input('enter a number: ')
    enter a number: 11001
    >>> int(binary, 2)
    25
    >>>
    

    However, if you cannot use int like that, then you could always do this:

    binary = raw_input('enter a number: ')
    decimal = 0
    for digit in binary:
        decimal = decimal*2 + int(digit)
    print decimal
    

    Below is a demonstration:

    >>> binary = raw_input('enter a number: ')
    enter a number: 11001
    >>> decimal = 0
    >>> for digit in binary:
    ...     decimal = decimal*2 + int(digit)
    ...
    >>> print decimal
    25
    >>>
    

提交回复
热议问题