pythonbinarydecimaltwos-complement

Converting an integer to signed 2's complement binary string


Right now, as far as I know, all means of conversion from int to binary bit string is for unsigned conversions (bin, format, etc.). Is there a way to quickly convert a given integer into its corresponding 2's complement bitstring (using minimal bits)?

For example, I'd want this function f to output:

f(-4) = '100'
f(5) = '0101'
f(-13) = '10011'

Right now, my implementation is this code here:

def f(x):
    """Convert decimal to two's complement binary string"""
    if x < 0:
        bs = bin(x)[3:]
        bs_pad = zero_pad(bs, roundup(tc_bits(x)))
        return bin((int(invert(bs_pad),2) + 1))#negate and add 1
    else: #Positive- sign bit 0.
        bs = bin(x)[2:]
        return "0b" + zero_pad(bs, roundup(tc_bits(x)))

which basically traces each step of the conversion process- zero-padding, negation, adding 1, then converting back to binary (it actually also ensures the bit width is a multiple of four). This was super tedious to write and I'm wondering if Python supports a faster/more code-concise way.


Solution

  • Nothing built in, but this is more concise:

    def f(n):
        nbits = n.bit_length() + 1
        return f"{n & ((1 << nbits) - 1):0{nbits}b}"
    

    Then, e.g.,

    >>> f(0)
    '0'
    >>> f(1)
    '01'
    >>> f(2)
    '010'
    >>> f(3)
    '011'
    >>> f(-1)
    '11'
    >>> f(-2)
    '110'
    >>> f(-3)
    '101'