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

Answer by Reza Abtin for Python int to binary string?

$
0
0

Yet another solution with another algorithm, by using bitwise operators.

def int2bin(val):    res=''    while val>0:        res += str(val&1)        val=val>>1     # val=val/2     return res[::-1]   # reverse the string

A faster version without reversing the string.

def int2bin(val):   res=''   while val>0:       res = chr((val&1) + 0x30) + res       val=val>>1       return res 

Viewing all articles
Browse latest Browse all 74

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>