how can I convert binary to decimal without using bin method

Viewed 68

whenever I run my code I get a TypeError saying "not all arguements converted during string formatting" and I tried using str() around what didn't get converted but I ran into more errors.

Here is my code:

def decimalToBinary(num):

bits = " "

while(num > 0):
   
    bits = str(num%2) + bits
    num = num//2
    
    return bits

def binaryToDecimal(bits):

    deciNum = 0
    powers = 0

    for i in reversed(bits):
    
        deciNum = 2 **powers** (bits % 10)
        bits /=  10
        powers += 1
    
        return deciNum

#program tester
for i in range(135, 146):
x = decimalToBinary(i)
deciNum = binaryToDecimal(x)
print(str(decimal))+ ' is '+ ' in Binary.'

I get this TypeError on the line that says "deciNum = 2 ** powers ** (bits%10)

2 Answers

Try this:

def binaryToDecimal(b_num: str) -> int:
    d_num = 0
    for i in range(len(b_num)):
        digit = b_num.pop()
        if digit == '1':
            d_num = d_num + 2**i
    return d_num

Note that b_num is a string, not an int. So you need to use this function in this way binaryToDecimal('101') (and not in this way binaryToDecimal(101)).

To answer the title of the post and to keep the types consistent with your program:

import math

def binaryToDecimal(bits):

    # Initialize integer for number.
    num = 0

    # For each bit, multiply by power of 2 corresponding to its position.
    #  Then, add that power of 2 to the total counter.
    for i in range(len(bits)):
        num += int(bits[i]) * (2 ** (len(bits)-i-1))

    # Return integer type.
    return str(num)

def decimalToBinary(num):

    # Determine how many bits represent the decimal number.
    num_of_bits = int(math.log(num, 2)) + 1

    bits = ''

    # Shift the number over 1 more place to the right in each iteration.
    #  Then test the sign of the bit with AND.
    for i in reversed(range(num_of_bits)):
        bits += str(int(1&(num>>i)))
    
    return bits


for i in range(135, 146):
    x = decimalToBinary(i)
    deciNum = binaryToDecimal(x)
    print(str(deciNum)+ ' is '+ str(x)+' in Binary.')
Related