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

Answer by DeanM for Convert int to binary string in Python

$
0
0

For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2's complement binary strings, this works:

def int2bin(integer, digits):    if integer >= 0:        return bin(integer)[2:].zfill(digits)    else:        return bin(2**digits + integer)[2:]

This produces:

>>> int2bin(10, 8)'00001010'>>> int2bin(-10, 8)'11110110'>>> int2bin(-128, 8)'10000000'>>> int2bin(127, 8)'01111111'

Viewing all articles
Browse latest Browse all 74

Trending Articles



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