Converting binary to decimal integer output

前端 未结 9 2345
暗喜
暗喜 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:42

    If you want/need to do it without int:

    sum(int(c) * (2 ** i) for i, c in enumerate(s[::-1]))
    

    This reverses the string (s[::-1]), gets each character c and its index i (for i, c in enumerate(), multiplies the integer of the character (int(c)) by two to the power of the index (2 ** i) then adds them all together (sum()).

提交回复
热议问题