Converting binary to decimal integer output

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

    There is actually a much faster alternative to convert binary numbers to decimal, based on artificial intelligence (linear regression) model:

    1. Train an AI algorithm to convert 32-binary number to decimal based.
    2. Predict a decimal representation from 32-binary.

    See example and time comparison below:

    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import train_test_split
    import numpy as np
    
    y = np.random.randint(0, 2**32, size=10_000)
    
    def gen_x(y):
        _x = bin(y)[2:]
        n = 32 - len(_x)
        return [int(sym) for sym in '0'*n + _x]
    
    X = np.array([gen_x(x) for x in y])
    
    model = LinearRegression()
    model.fit(X, y)
    
    def convert_bin_to_dec_ai(array):
        return model.predict(array)
    
    y_pred = convert_bin_to_dec_ai(X)
    

    Time comparison:

    This AI solution converts numbers almost x10 times faster than conventional way!

    0 讨论(0)
  • 2021-02-13 17:38

    Binary to Decimal

    int(binaryString, 2)
    

    Decimal to Binary

    format(decimal ,"b")
    
    0 讨论(0)
  • 2021-02-13 17:39

    The input may be string or integer.

    num = 1000  #or num = '1000'  
    sum(map(lambda x: x[1]*(2**x[0]), enumerate(map(int, str(num))[::-1])))
    
    # 8
    
    0 讨论(0)
  • 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()).

    0 讨论(0)
  • 2021-02-13 17:42
    a = input('Enter a binary number : ')
    ar = [int(i) for  i in a]
    ar  = ar[::-1]
    res = []
    for i in range(len(ar)):
        res.append(ar[i]*(2**i))
    sum_res = sum(res)      
    print('Decimal Number is : ',sum_res)
    
    0 讨论(0)
  • 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
    >>>
    
    0 讨论(0)
提交回复
热议问题