Zac Perry
Zac Perry

Reputation: 101

Convert int to binary in JES?

I'm trying to convert an int to a binary string. This would be super easy with the bin() function, but this is not available in JES, which uses Jython 2.5.2.

I tried using this:

def convertToBinary(n):
   string = ''
   if n > 1:
     convertToBinary(n//2)
   string = string  + str(n%2)
   print string

dec = 34
convertToBinary(dec)
print()

but str() is not converting it. I try removing str, thinking somehow n % 2 is already a string, but nope.

Any ideas?

Upvotes: 0

Views: 79

Answers (1)

Bilesh Ganguly
Bilesh Ganguly

Reputation: 4141

You can either use a ternary operation.

def convertToBinary(n):
    s = ""
    if n > 1:
        convertToBinary(n // 2)
    s = s + ("0" if n % 2 == 0 else "1")
    print s

Or, you can use the Java way of converting integers into a string.

import java.lang

def convertToBinary(n):
    s = ""
    if n > 1:
        convertToBinary(n // 2)
    s = s + java.lang.String.valueOf(n % 2)
    print s

Upvotes: 0

Related Questions