AdvancedMath for DSABit Manipulation & Math

Two's complement: how negative numbers live in bits

−x is ~x + 1, so −1 is all ones. x & −x isolates the lowest set bit. And Python needs a mask to act like 32-bit ints.

The idea

Computers store negative integers as : flip every bit and add 1. In 8 bits, 5 = 00000101 and −5 = 11111011. Adding them gives 0 with the carry falling off the end, which is why the CPU can use one adder for both.

Handy consequences: −1 is all ones; x & −x keeps only the lowest set bit (used by Fenwick trees). Python ints are unbounded, so to mimic 32-bit you mask with & 0xFFFFFFFF and convert back if the top bit is set.

Worked example

x & −x for x = 12

  1. 12 = 01100. −12 = flip (10011) + 1 = 10100.
  2. 01100 & 10100 = 00100 = 4: the lowest set bit of 12.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

−x = (flip every bit of x) + 1
lowest set bit of x = x AND −x
32-bit wrap (Python):
x ← x AND 0xFFFFFFFF
if bit 31 is set: x ← x − 2³²

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

x = 12, shown in 5 bits

x = 1201100

Solution · Pythonline 13

MASK = 0xFFFFFFFF
def to_int32(x):
x &= MASK
return x - (1 << 32) if x >> 31 else x
def add_without_plus(a, b): # Sum of Two Integers
a, b = a & MASK, b & MASK
while b:
a, b = (a ^ b) & MASK, ((a & b) << 1) & MASK
return to_int32(a)
def lowest_bit(x):
return x & -x

Step 1 of 4· line 13

12 in binary is 01100. Negative numbers are stored in two's complement: −x = flip every bit, then add 1.

O(32) per addition: constant.

How to spot it

  • Bit problems with negative inputs, “without using + or −”, reversing or counting bits of signed ints.

Common mistakes

  • Python loops forever on negative numbers in bit loops without a mask.
  • Assuming >> on negatives fills with zeros: Python and Java's >> keep the sign.

Practise the ideas first

Where it comes up

Go further