1

I encountered an issue with my Python script that converts binary to decimals. The caveat with this script is that I can only use basic computational functions (+, -, *, /, **, %, //), if/else, and for/while loops.

Shown below is my script:

x = int(input("Enter your binary input: "))
z=0

while x != 0:

    for y in range (0,20):
        
        if (x % 2 == 0):
            z += 0*2**y
            x = int(x/10)
            
        
        elif (x % 2 != 0):
            z += 1*2**y
            x = int(x/10)

print(z)

While my script works for binaries with short length (e.g., 1101 = 13), it does not work for long binaries (especially those that have a length of 20). For example, inputting a binary of 11111010010011000111, my script returns an output of 1025217 instead of 1025223.

Can anyone point me to my mistake?

Thank you in advance!

3 Answers 3

2

Floating arithmetic isn't perfect and has a precision limit.

11111010010011000111 / 10 gives 1.1111010010011e+18, which when converted to an integer will give you a wrong result and it snowballs from there.

>>> int(11111010010011000111 / 10)
1111101001001100032

The more binary digits you have, the more "off" your calcuations will be.

In order to avoid the problem you encountered, use floor division, ie, x // 10.

Or you can skip turning x into a number and do the necessary power calculations based off each binary digit and its position.

x = input("Enter your binary input: ")[::-1]

n = 0
# this would be more elegant with `enumerate()`, but I assume you can't use it
# same for `sum()` and a comprehension list
for i in range(len(x)):
    n += int(x[i])*2**i
print(n)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the following method

to multiple each of the binary digits with its corresponding value of 2 raised to the power to its index (position from right – 1) and sum them up.

binary = input('Binary number: ')
decimal = 0
binary_len = len(binary)

for x in binary:
    binary_len = binary_len - 1
    decimal += pow(2,binary_len) * int(x)
    
print(decimal)

input : 11111010010011000111

output : 1025223

More examples

Comments

0

You should not use int to convert any number if you have to write a number converter. Just use string operations:

digits = input("Enter your binary input: ")
number = 0
for digit in digits:
    number = number * 2 + (digit == "1")
print(number)

output

Enter your binary input: 11111010010011000111
1025223

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.