Quantcast
Viewing latest article 31
Browse Latest Browse All 74

Answer by Martin Thoma for Convert int to binary string in Python

If you want a textual representation without the 0b-prefix, you could use this:

get_bin = lambda x: format(x, 'b')print(get_bin(3))>>> '11'print(get_bin(-3))>>> '-11'

When you want a n-bit representation:

get_bin = lambda x, n: format(x, 'b').zfill(n)>>> get_bin(12, 32)'00000000000000000000000000001100'>>> get_bin(-12, 32)'-00000000000000000000000000001100'

Alternatively, if you prefer having a function:

def get_bin(x, n=0):"""    Get the binary representation of x.    Parameters    ----------    x : int    n : int        Minimum number of digits. If x needs less digits in binary, the rest        is filled with zeros.    Returns    -------    str"""    return format(x, 'b').zfill(n)

Viewing latest article 31
Browse Latest Browse All 74

Trending Articles