Quantcast
Channel: Convert int to binary string in Python - Stack Overflow
Viewing all articles
Browse latest Browse all 74

Answer by Kyle Siopiolosz for Python int to binary string?

$
0
0

Along a similar line to Yusuf Yazici's answer

def intToBin(n):    if(n < 0):        print "Sorry, invalid input."    elif(n == 0):        print n    else:        result = ""        while(n != 0):            result += str(n%2)            n /= 2        print result[::-1]

I adjusted it so that the only variable being mutated is result (and n of course).

If you need to use this function elsewhere (i.e., have the result used by another module), consider the following adjustment:

def intToBin(n):    if(n < 0):        return -1    elif(n == 0):        return str(n)    else:        result = ""        while(n != 0):            result += str(n%2)            n //= 2            #added integer division        return result[::-1]

So -1 will be your sentinel value indicating the conversion failed. (This is assuming you are converting ONLY positive numbers, whether they be integers or longs).


Viewing all articles
Browse latest Browse all 74

Trending Articles