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()
4 Answers 4
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.
3 Comments
n >> 1 ... n >> 2 divides by 4What about the build-in function "bin"?
>>> bin(4711)
'0b1001001100111'
Batteries included!
Comments
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
The problem here is that if n>0, should be a while loop, not an if statement.
bin(). (You may need to strip off the leading0bfrom the result, depending on your purposes.)