1

I am trying to created a function that takes in a Decimal represented value and converts it into Binary represented value.

Assuming the argument is always an integer:

import math

def binary_decimal_converter(x):

    binary_representation = 0
    number = x

    while number != 0:
        n = 1
        while x not in range(n,n*2):
            n *= 2
        binary_representation += 10**(int(math.log(n,2)))
        number -= n

    return binary_representation

The problem:

If x is in the list below, the program runs normally.

[1, 2, 4, 8, 16, 32, 64, 128....]

But if any other number is used, the program gets stuck in an unbreakable loop.

Why the loop:

while number != 0: #line 24  

cannot run twice?

4
  • Can number be 0 if x=3? Commented Dec 17, 2018 at 19:06
  • 1
    Unless this is homework, why not just bin(x)[2:] ? Commented Dec 17, 2018 at 19:13
  • @QuangHoang supposedly, yes. The first time n = 2 and number -= 2. The second time n = 1 and number -= 1. Then number == 0 Commented Dec 17, 2018 at 19:17
  • @JohnColeman It is a homework. Commented Dec 17, 2018 at 19:18

1 Answer 1

1

You're assigning number = x and then using both:

import math

def binary_decimal_converter(x):
    binary_representation = 0
    number = x

    while number != 0:
        n = 1
        while x not in range(n,n*2): # CHANGE x TO number
            n *= 2
        binary_representation += 10**(int(math.log(n,2)))
        number -= n

    return binary_representation

If you change x to number on the specified line, it works. x is not being updated, number is.

Sign up to request clarification or add additional context in comments.

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.