1

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.

1
  • Yes that's my mistake, edited Commented Aug 6, 2020 at 0:12

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure why you don't include the front 1s. Here is a solution with those 1s, slow but easier to understand than bit operations

def f(val, byte_len=1):
    int_complement = val + (256**byte_len)*(val<0)
    bin_complement = format(int_complement, 'b')
    return bin_complement 
f(-1)
'11111111'
f(-4)
'11111100'
f(5)
'101'
f(-13)
'11110011'
f(-13, byte_len=2)
'1111111111110011'

# Bonus: the reverse way too:
def twos_complement(val, byte_len=1):
    return val + (256**byte_len)*(val<0)

def reverse_twos_complement(val, byte_len=1):
    return val - (256**byte_len)*(val>(256**byte_len/2)-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.