0

Hello I am a beginner in Python. I wrote the following code to convert a number in to a bynary number. I use T to count how many times the number can be devide by two. The remainder R is used again in the inner loop, but then I have to set T to 0, if I do this I get in to an infinite loop .... Can someone help me with this?

import math

T=0 # timer to count homany times the given number can be divided by 2

G= int(input("nummer "))

A=G # save G in A, we need G later
R=G # the remainder also initialized with G

while R>1:
    print(T)
    while A>1:   
        A=int(A/2)
        T=T+1

        print(T)
        print(A)

    R=int(G-math.pow(2,T))

    A=R #use the remainder agin in the inner loop
    T=0 #set T to O, here it goes wrong, ill get an infinite loop!!! why
Florin Stingaciu
  • 8,085
  • 2
  • 24
  • 45
  • Note that Python actually has this functionality built in: https://docs.python.org/2/library/functions.html#bin – Brad Beattie Jul 17 '14 at 20:08
  • There is a similar post on this issue: [PreviousQuestion](http://stackoverflow.com/questions/10411085/converting-integer-to-binary-in-python) – rch Jul 17 '14 at 20:15

1 Answers1

0

You only need one loop for this. Also, you can use the modulo operator (%).

The general gist of it is...You want to keep dividing the number by 2, until you get to 0. As you go, you want to add the REMAINDER (calculated by the % operator) as you go.

I don't program in python. (Not sure about indentation, appending to a list, int(input("nummer ")), Which I am assuming is the number you want to convert.)

listToStoreAnswerInReverse = []
theNumberToConvert = int(input("nummer "))

while(theNumberToConvert != 0)
    remainder = theNumberToConvert % 2
    listToStoreAnswerInReverse.append([remainder])
    theNumberToConvert = theNumberToConvert / 2

listToStoreAnswerInReverse should now have the answer in binary. Keep in mind, this answer will be in reverse. So the first index on the list will contain the last value in binary.

This is one of a few methods of doing this problem. You can use the built in as suggested or use descending power of 2's and subtracting. But I'm not sure how to do that without more research.

jgvb
  • 304
  • 5
  • 16