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()
The problem here is:
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
EDIT2: The comment form John Machin is correct, and I fixed the above to reflect that.