1

I'm writing a program to calculate the binary number from an integer input. I cannot figure out how to reverse the output code to show what the binary number would be. The program below works but does not output the bits in the right order.

For example, when I enter 156, the answer should be the reverse of 00111001, but I cannot get the program to output this backwards to show 10011100.

  1. This should be a program to calculate binary number from an integer.
    It should prompt a user to enter an integer number = int(input("Enter number: ")) and calculate the binary number or give a warning if an incorrect number type was entered.

    if number > 0:
      while number != 0:
        if number % 2 == 0:
            code = "0"
            new_number = number //2
            number = new_number
        else:
            code = "1"
            new_number = number //2
            number = new_number
        reverse_code = code[::-1]
        print(reverse_code, end='') else:
      print ("Invalid Input. System will now self-destruct.")
    
zx485
  • 28,498
  • 28
  • 50
  • 59
  • Your reverse code always seems to be getting the value "1". – hshantanu Oct 18 '18 at 18:36
  • Possible duplicate of [Python int to binary?](https://stackoverflow.com/questions/699866/python-int-to-binary) – jar Oct 18 '18 at 18:41
  • @raj I don't think so, this may be for an assignment to make sure OP knows how to convert a decimal number to binary the old-fashioned way. Of course, using `bin` or string formatting is much simpler. – Joel Oct 18 '18 at 19:57

1 Answers1

1

You are printing each element (1 or 0) into the loop. You should concatenate all the 1/0s and reverse at the end.

Pay attention when you program loops. You are trying to set a value which is built along iterations in a specific iteration. When your script calculates code value (for example 1), it reverses that number and jumps to the next iteration, repeating the process.

The solution would be to build an inverse string along all iterations, incrementally. The next code defines an empty string and concatenates 0 or 1 before the previous result.

Example:

# Initialize reverse_code variable
reverse_code = ""

while number != 0:
    if number % 2 == 0:
        code = "0"
        new_number = number //2
        number = new_number
    else:
        code = "1"
        new_number = number //2
        number = new_number
    reverse_code = code + reverse_code
print(reverse_code)

If number = 10:

1010

Explanation

When while loop starts iterating, it divides by 2 the number and we want to reverse the result of the division to obtain binary code. Instead of calculate the result we can create the result in calculation time. For this we define reverse_code as an empty string. In each iteration we will put the new item (1 or 0) before the string, obtaining the inverse string.

reverse_code values in iterations when number=10:

Iteration 0: code = 0 reverse_code = code+ reverse_code = "0" + "" = "0"

Iteration 1: code = 1 reverse_code = code+ reverse_code = "1" + "0" = "10"

....

Iteration N:

code = 1 reverse_code = code+ reverse_code = "1" + "010" = "1010"

Another question to comment is your code optimization. Watching your code, if the else-if you have new_number and number variables assignation which is not affected by the previous variables code. You can extract common factor and simplify the code. The code should be as follows:

# Initialize reverse_code variable
reverse_code = ""

while number != 0:
    
    # Calculate the `code` value
    if number % 2 == 0:
        code = "0"
    else:
        code = "1"

    # Putting this here simplifies duplicate instructions
    new_number = number //2
    number = new_number
     
    # Putting 0 or 1 (code) before semi-built string (reverse_code) 
    reverse_code = code + reverse_code

print(reverse_code)
Community
  • 1
  • 1
Marco
  • 670
  • 5
  • 16
  • Thank you so much @Marco! I had a feeling it had to do with not concatenating the results from the loop but could not figure out the work around. Just getting started in Python so I have a lot still to learn. This was my first attempt to write a program on my own. Really appreciate the feedback!! – Jenna Shannon Oct 19 '18 at 19:37