1

I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0. which is definitely wrong. Can you guys help out? I'm using python 3 by the way.

def ConvertNtoBinary(n):

    binaryStr = ''
    if n < 0:
        print('Value is a negative integer')

    if n == 0:
        print('Binary value of 0 is 0')
    else:
        if n > 0:
            binaryStr = str(n % 2) + binaryStr
            n = n > 1
    return binaryStr

def main():
    n = int(input('Enter a positive integer please: '))
    binaryNumber = ConvertNtoBinary(n)
    print('n converted to a binary number is: ',binaryNumber)

main()
1
  • I'm assuming you're doing this either as homework or for your own enjoyment/exercise, which is great. If you just want something that works, use the built-in function bin(). (You may need to strip off the leading 0b from the result, depending on your purposes.) Commented Mar 13, 2012 at 20:06

4 Answers 4

3

The problem here is:

n = n > 1

This does the boolean comparison "is n greater than 1?". What you likely want is n >> 1, which bitshifts n.

EDIT: Also, you're only doing this process once - I imagine you'll want to do it on some condition, like

while n > 0:

EDIT2: The comment form John Machin is correct, and I fixed the above to reflect that.

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

3 Comments

I think i got it. Is 6 converted to binary, 110?
indeed it is: (2^0)*0 + (2^1)*1 + (2^2)*1 = 2 + 4 = 6
You mean n >> 1 ... n >> 2 divides by 4
0

What about the build-in function "bin"?

>>> bin(4711)
'0b1001001100111'

Batteries included!

Comments

0

It depends on what you are doing, but the Python function for doing this is bin(). If you want to convert to binary, you can do bin(numbertoconvert). If you want to convert from binary, you can do int(numbertoconvert, 2). int() takes an optional argument of what base it uses. To get a regular binary number from bin(), you can do int(bin(numbertoconvert)[2:])

Comments

0

The problem here is that if n>0, should be a while loop, not an if statement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.