M33 · Bit Manipulation

Bits, Masks and Two’s Complement

An integer is a row of bits, and the bitwise operators edit that row directly. This lesson covers masks, the x & (x − 1) family of tricks, two’s complement negation and the three right-shift behaviours, with the signed-shift, unbounded-int and undefined-behaviour rules of C#, Java, Python and C++.

~45 minIntermediateC# · Python · Java · C++
Curriculum: M33 Bit Manipulation · 1 of 1 lessons available

You will be able to

  • Build a mask for bit i and use OR, AND NOT and XOR to set, clear and toggle it.
  • Explain why x & (x − 1) clears the lowest set bit and x & −x isolates it, and use both.
  • Count set bits with Kernighan’s loop and state its running time in terms of the number of 1 bits.
  • Read a bit pattern as unsigned and as two’s complement, and negate a value with ~x + 1.
  • Choose between logical and arithmetic right shift in each language and avoid shift-count pitfalls.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A fixed-width integer is a row of w bits, bit 0 on the right. Its unsigned value is Σ bitᵢ · 2ⁱ. The bitwise operators work on every position at once, without carries:

Operator Bit rule Typical use
a & b 1 if both are 1 keep only the bits a mask selects; test a bit
a | b 1 if either is 1 turn bits on
a ^ b 1 if they differ flip bits; XOR twice restores
~a flip every bit invert a mask
a << k move bits up k places, zeros in from the right multiply by 2ᵏ (modulo 2ʷ)
a >> k move bits down k places divide by 2ᵏ, rounding down

A mask is a value whose 1 bits select positions. 1 << i selects bit i alone; (1 << k) − 1 selects the low k bits.

The lab runs a list of operations on one value of 8, 16 or 32 bits and draws three rows: x, the operand (mask, x − 1, ~x, −x), and the result.

One bit at a time

set(x, i)    = x | (1 << i)
clear(x, i)  = x & ~(1 << i)
toggle(x, i) = x ^ (1 << i)
test(x, i)   = (x >> i) & 1

Each one changes or reads bit i and leaves every other bit as it was: OR with 0, AND with 1 and XOR with 0 are identities. Bit sets built this way are a compact replacement for bool[]: 64 flags in one machine word, and union, intersection and difference become one instruction each (|, &, & ~). That is how BitArray, java.util.BitSet and std::bitset work inside.

The x − 1 tricks

Subtracting 1 turns the lowest 1 bit into 0 and every 0 below it into 1:

x     = 1011 0100
x − 1 = 1011 0011

So:

  • x & (x − 1) clears the lowest set bit: 1011 0000.
  • x & (x − 1) == 0 (with x ≠ 0) means x has exactly one 1 bit: x is a power of two. The x ≠ 0 check matters, because 0 & (0 − 1) is also 0.
  • x & −x isolates the lowest set bit: 0000 0100. In two's complement, −x = ~x + 1 flips every bit above the lowest 1 and keeps that 1 (see below). Fenwick trees step through indices with exactly this expression.

Kernighan's popcount

count = 0
while x != 0:
    x = x & (x - 1)        # clears one 1 bit
    count = count + 1
return count

The loop runs once per set bit, not once per bit position: popcount(180) = popcount(1011 0100) takes four iterations, not eight (preset Popcount). Worst case O(w), when every bit is 1. Real code calls the built-in, which compiles to a single instruction on modern CPUs: BitOperations.PopCount, Integer.bitCount, int.bit_count() (Python 3.10+), std::popcount (C++20).

Two's complement

Signed integers use the same bits with one change: the top bit counts −2ʷ⁻¹ instead of +2ʷ⁻¹. In 8 bits, 1111 1011 is 251 unsigned and −128 + 123 = −5 signed. The range is −2ʷ⁻¹ … 2ʷ⁻¹ − 1.

Negation is "invert, then add one": −x = ~x + 1. Because x + ~x is all ones (= −1), x + (~x + 1) = 0. Consequences worth knowing:

  • Addition and subtraction are the same circuit for signed and unsigned values; only comparisons, division, widening and printing differ.
  • The most negative value has no positive partner: in 8 bits, −(−128) is −128 again (preset Two's complement). Math.abs(Integer.MIN_VALUE) in Java returns a negative number for the same reason.
  • Widening a signed value copies the sign bit into the new high bits (sign extension); widening an unsigned value fills them with zeros.

Shifts: logical versus arithmetic

Shifting right by k divides by 2ᵏ, but what comes in from the left differs:

  • Logical right shift fills with zeros: unsigned division. 1111 0000 >>> 2 = 0011 1100 (60).
  • Arithmetic right shift copies the sign bit: signed division rounding toward −∞. 1111 0000 (−16) >> 2 = 1111 1100 (−4). Note −7 >> 1 = −4, while −7 / 2 = −3 in C#, Java and C++ (they round toward zero); Python's // also rounds toward −∞, so −7 >> 1 == −7 // 2 there.

Left shift is the same for both: zeros come in, and bits that move past the top are lost (preset Shifts).

Language notes

C#. int and long are signed, uint and ulong unsigned. >> is arithmetic on signed and logical on unsigned types; C# 11 added >>>, always logical. The shift count is masked to the operand width: x << 32 on an int equals x << 0, not 0 (the C# test checks this). Overflow wraps silently unless you are inside checked. On a uint, -x widens to long, so the listing writes x & −x as x & (~x + 1). Built-ins live in System.Numerics.BitOperations.

Java. Every integer type is signed (except char); there is no uint. >> is arithmetic, >>> logical. Shift counts are masked to 5 bits for int and 6 for long. To treat an int as unsigned, use Integer.toUnsignedLong, Integer.compareUnsigned, Integer.divideUnsigned. byte is signed too: mask with & 0xFF before using a byte as a number (the UTF-8 test does). Built-ins: Integer.bitCount, Integer.lowestOneBit, Integer.numberOfTrailingZeros.

Python. int is unbounded: there is no width, no overflow, and 1 << 100 is fine. A negative int behaves as if it had infinitely many leading 1 bits, so ~5 == -6 and -8 >> 1 == -4 (arithmetic). To model a w-bit register, mask every result that can grow or go negative with & ((1 << w) - 1), and convert to signed with x - (1 << w) if x >> (w - 1) else x. The listing masks after shift left and negation; x.bit_count() and x.bit_length() are the built-ins.

C++. Unsigned arithmetic wraps modulo 2ʷ and is always defined; signed overflow is undefined behaviour. Shifting by a count ≥ the width of the promoted type is undefined, which is why mask(32) is a special case instead of (1u << 32) − 1. Before C++20, right-shifting a negative signed value and converting an out-of-range unsigned value to a signed type were implementation-defined, and left-shifting a negative value was undefined; since C++20 integers are defined to be two's complement, >> on a negative value is arithmetic, and the conversion is modular, which the listing's to_signed relies on. Small types promote: ~std::uint8_t{5} is the int −6, not 250, so cast or mask the result. <bit> (C++20) has std::popcount, std::has_single_bit, std::countr_zero; use unsigned types with them.

Arithmetic >> Logical >> Shift count ≥ width Unsigned types
C# on signed on unsigned, or >>> masked yes
Java >> >>> masked no (helpers)
Python >> (only kind) mask first fine (unbounded) no width at all
C++ on signed (defined since C++20) on unsigned undefined yes

The teaching implementation

All four listings keep the value in an unsigned (C#, C++), signed int (Java) or unbounded (Python) container and mask to the chosen width. One shared fixture runs operation sequences in 8, 16 and 32 bits; its expected values were computed with plain arithmetic (multiplication, floor division, modulo 2ʷ), not with the tricks being tested. Each language also compares 20,000 random values with its built-in popcount, lowest-bit and power-of-two functions and with arithmetic for shifts and negation.

Common mistakes

  • Precedence. In C#, Java and C++, == binds tighter than &, so x & 1 == 0 means x & (1 == 0) (a compile error in C# and Java, a silent bug in C++). Parenthesise: (x & 1) == 0. Python is the exception: comparisons bind looser than &.
  • Forgetting x ≠ 0 in the power-of-two test.
  • Using >> on a signed negative value when you meant a logical shift, for example when extracting fields from a packed value.
  • 1 << 31 in Java or C# is negative, and 1 << 32 is 1; in C++ 1 << 31 on a 32-bit int was undefined in C++11 (C++14 and C++17 made it implementation-defined; only C++20 fully defines it). Write 1u << i or 1L << i as needed.
  • Assuming Python ints wrap. They never do; without a mask, x << 1 just grows.

Edge cases

  • x = 0: popcount 0, no lowest bit (x & −x = 0), not a power of two.
  • All ones: popcount w; as signed it is −1, and arithmetic shifts leave it unchanged.
  • The sign bit alone (2ʷ⁻¹): a power of two as unsigned, the most negative value as signed, its own negation.
  • Shift by 0 returns x unchanged in every language.

Worked practice

1. In 8 bits, what are x & (x − 1) and x & −x for x = 0110 1000?

Answer

x − 1 = 0110 0111, so x & (x − 1) = 0110 0000. −x = 1001 1000, so x & −x = 0000 1000 (bit 3).

2. How many iterations does Kernighan's loop take for 0x80000001?

Answer

Two: the value has two set bits. A loop over all positions would take 32.

3. What is 1111 0110 as an 8-bit signed value, and what is its negation?

Answer

−128 + 118 = −10. ~x + 1 = 0000 1001 + 1 = 0000 1010 = 10.

4. Swap two variables with XOR. Why is it rarely a good idea?

Answer

a ^= b; b ^= a; a ^= b; works because XOR twice restores. It is slower than a temporary on modern CPUs, harder to read, and sets both to 0 if a and b are the same variable (aliasing).

Summary

  • Masks plus OR, AND NOT and XOR set, clear and toggle single bits; (x >> i) & 1 reads one.
  • x & (x − 1) clears the lowest 1, x & −x isolates it; Kernighan's popcount loops once per set bit.
  • Two's complement: the top bit is negative, −x = ~x + 1, and the minimum has no positive partner.
  • Logical shifts bring in zeros, arithmetic shifts copy the sign; check each language's shift-count and signedness rules before relying on either.

Full implementation

Every operation in four languages, checked against one shared fixture of 8-, 16- and 32-bit operation sequences (expected values computed with plain arithmetic) and 20,000 random values compared with the built-in popcount, lowest-bit and power-of-two functions and with multiplication, floor division and modulo for the shifts and negation.

namespace Bekadan.Dsa.Examples.Bits;
 
/// <summary>
/// Bit operations on a fixed-width unsigned value held in a <see cref="uint"/>
/// (width 1–32; bits above the width are always 0). Index and shift arguments
/// must be below the width: C# masks a 32-bit shift count to 5 bits, so
/// <c>x &lt;&lt; 32</c> is <c>x</c>, not 0. The built-ins are
/// <see cref="System.Numerics.BitOperations"/> (PopCount, IsPow2, TrailingZeroCount).
/// </summary>
public static class BitOps
{
    /// <summary>All ones in the low <paramref name="width"/> bits (1u &lt;&lt; 32 would be 1u, hence the branch).</summary>
    public static uint Mask(int width) => width == 32 ? uint.MaxValue : (1u << width) - 1;
 
    public static uint SetBit(uint x, int i)
    {
        return x | (1u << i);
    }
 
    public static uint ClearBit(uint x, int i)
    {
        return x & ~(1u << i);
    }
 
    public static uint ToggleBit(uint x, int i)
    {
        return x ^ (1u << i);
    }
 
    public static bool TestBit(uint x, int i)
    {
        return ((x >> i) & 1) != 0;
    }
 
    /// <summary>x &amp; −x. On a uint, <c>-x</c> would widen to long, so write −x as ~x + 1.</summary>
    public static uint LowestSetBit(uint x)
    {
        return x & (~x + 1);
    }
 
    /// <summary>Kernighan: each x &amp;= x − 1 clears the lowest 1 bit, so the loop runs once per set bit.</summary>
    public static int PopCount(uint x)
    {
        int count = 0;
        while (x != 0)
        {
            x &= x - 1;
            count++;
        }
        return count;
    }
 
    public static bool IsPowerOfTwo(uint x)
    {
        return x != 0 && (x & (x - 1)) == 0;
    }
 
    /// <summary>Two's complement: −x is ~x + 1, reduced to the width (unchecked wrap-around is the default).</summary>
    public static uint Negate(uint x, int width)
    {
        return (~x + 1) & Mask(width);
    }
 
    public static uint ShiftLeft(uint x, int k, int width)
    {
        return (x << k) & Mask(width);  // bits shifted past the width are dropped
    }
 
    /// <summary>Logical: zeros come in from the left. On a uint, &gt;&gt; is already logical (C# 11 also has &gt;&gt;&gt;).</summary>
    public static uint ShiftRightLogical(uint x, int k)
    {
        return x >> k;
    }
 
    /// <summary>Arithmetic: copies of the sign bit come in. On an int, &gt;&gt; is arithmetic.</summary>
    public static uint ShiftRightArithmetic(uint x, int k, int width)
    {
        return (uint)(ToSigned(x, width) >> k) & Mask(width);
    }
 
    /// <summary>The same bits read as a signed two's-complement value of the given width.</summary>
    public static int ToSigned(uint x, int width) => (int)(x << (32 - width)) >> (32 - width);
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Bits/BitOps.cs

"""Bit operations on a fixed-width unsigned value.
 
Python ints are unbounded: there is no overflow and no fixed width, and a
negative int behaves as if it had infinitely many leading 1 bits. To model an
8-, 16- or 32-bit register, every operation that can produce bits above the
width (shift left, negate) masks its result with (1 << width) - 1. Built-ins:
int.bit_count() (3.10+), int.bit_length().
"""
 
 
def mask(width: int) -> int:
    return (1 << width) - 1
 
 
def set_bit(x: int, i: int) -> int:
    return x | (1 << i)
 
 
def clear_bit(x: int, i: int) -> int:
    return x & ~(1 << i)  # ~(1 << i) is negative, but x & it keeps x non-negative
 
 
def toggle_bit(x: int, i: int) -> int:
    return x ^ (1 << i)
 
 
def test_bit(x: int, i: int) -> bool:
    return (x >> i) & 1 == 1
 
 
def lowest_set_bit(x: int) -> int:
    return x & -x
 
 
def pop_count(x: int) -> int:
    """Kernighan: each x &= x - 1 clears the lowest 1 bit (x must be non-negative)."""
    count = 0
    while x != 0:
        x &= x - 1
        count += 1
    return count
 
 
def is_power_of_two(x: int) -> bool:
    return x != 0 and x & (x - 1) == 0
 
 
def negate(x: int, width: int) -> int:
    """Two's complement -x of a width-bit value; without the mask, Python would return a negative int."""
    return (~x + 1) & mask(width)
 
 
def shift_left(x: int, k: int, width: int) -> int:
    return (x << k) & mask(width)  # Python never drops bits on its own
 
 
def shift_right_logical(x: int, k: int) -> int:
    return x >> k  # x is non-negative, so zeros come in
 
 
def shift_right_arithmetic(x: int, k: int, width: int) -> int:
    return (to_signed(x, width) >> k) & mask(width)  # >> on a negative int rounds toward -infinity
 
 
def to_signed(x: int, width: int) -> int:
    """The same bits read as a signed two's-complement value."""
    return x - (1 << width) if x >> (width - 1) else x

Tested on CPython 3.14.0 · examples/python/dsa_examples/bit_ops.py

package dev.bekadan.dsa.bits;
 
/**
 * Bit operations on a fixed-width unsigned value (width 1-32) kept in an
 * {@code int}. Java has no unsigned int type: the bits are the same, but
 * comparisons, division and printing read them as signed, so use
 * {@code >>>}, {@link Integer#toUnsignedLong} and {@link Integer#compareUnsigned}.
 * A shift count is masked to 5 bits ({@code x << 32 == x}), so index and
 * shift arguments must be below the width. Built-ins: {@link Integer#bitCount},
 * {@link Integer#lowestOneBit}.
 */
public final class BitOps {
    private BitOps() {
    }
 
    /** All ones in the low {@code width} bits ({@code 1 << 32} would be 1, hence the branch). */
    public static int mask(int width) {
        return width == 32 ? -1 : (1 << width) - 1;
    }
 
    public static int setBit(int x, int i) {
        return x | (1 << i);
    }
 
    public static int clearBit(int x, int i) {
        return x & ~(1 << i);
    }
 
    public static int toggleBit(int x, int i) {
        return x ^ (1 << i);
    }
 
    public static boolean testBit(int x, int i) {
        return ((x >>> i) & 1) != 0;
    }
 
    public static int lowestSetBit(int x) {
        return x & -x;
    }
 
    /** Kernighan: each x &amp;= x - 1 clears the lowest 1 bit, so the loop runs once per set bit. */
    public static int popCount(int x) {
        int count = 0;
        while (x != 0) {
            x &= x - 1;
            count++;
        }
        return count;
    }
 
    public static boolean isPowerOfTwo(int x) {
        return x != 0 && (x & (x - 1)) == 0; // also true for 1 << 31, which is negative as an int
    }
 
    /** Two's complement: -x is ~x + 1, reduced to the width (int arithmetic wraps silently). */
    public static int negate(int x, int width) {
        return (~x + 1) & mask(width);
    }
 
    public static int shiftLeft(int x, int k, int width) {
        return (x << k) & mask(width); // bits shifted past the width are dropped
    }
 
    /** Logical: zeros come in from the left. */
    public static int shiftRightLogical(int x, int k) {
        return x >>> k;
    }
 
    /** Arithmetic: copies of the sign bit come in. */
    public static int shiftRightArithmetic(int x, int k, int width) {
        return (toSigned(x, width) >> k) & mask(width);
    }
 
    /** The same bits read as a signed two's-complement value of the given width. */
    public static int toSigned(int x, int width) {
        return (x << (32 - width)) >> (32 - width);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/bits/BitOps.java

#pragma once
 
#include <cstdint>
 
namespace bekadan::dsa {
 
// Bit operations on a fixed-width unsigned value (width 1-32) kept in a
// std::uint32_t. Unsigned arithmetic wraps modulo 2^32 and is always defined.
// Shifting by a count >= the width of the (promoted) type is undefined
// behaviour, so index and shift arguments must be below the width.
// Built-ins (C++20 <bit>): std::popcount, std::has_single_bit, std::countr_zero.
 
// All ones in the low `width` bits (1u << 32 would be undefined, hence the branch).
constexpr std::uint32_t mask(int width) { return width == 32 ? 0xFFFFFFFFu : (std::uint32_t{1} << width) - 1; }
 
constexpr std::uint32_t set_bit(std::uint32_t x, int i) {
    return x | (std::uint32_t{1} << i);
}
 
constexpr std::uint32_t clear_bit(std::uint32_t x, int i) {
    return x & ~(std::uint32_t{1} << i);
}
 
constexpr std::uint32_t toggle_bit(std::uint32_t x, int i) {
    return x ^ (std::uint32_t{1} << i);
}
 
constexpr bool test_bit(std::uint32_t x, int i) {
    return ((x >> i) & 1u) != 0;
}
 
constexpr std::uint32_t lowest_set_bit(std::uint32_t x) {
    return x & (0u - x);  // unsigned negation wraps: well defined
}
 
// Kernighan: each x &= x - 1 clears the lowest 1 bit, so the loop runs once per set bit.
constexpr int pop_count(std::uint32_t x) {
    int count = 0;
    while (x != 0) {
        x &= x - 1;
        ++count;
    }
    return count;
}
 
constexpr bool is_power_of_two(std::uint32_t x) {
    return x != 0 && (x & (x - 1)) == 0;
}
 
// Two's complement: -x is ~x + 1, reduced to the width.
constexpr std::uint32_t negate(std::uint32_t x, int width) {
    return (~x + 1u) & mask(width);
}
 
constexpr std::uint32_t shift_left(std::uint32_t x, int k, int width) {
    return (x << k) & mask(width);  // bits shifted past the width are dropped
}
 
// Logical: on an unsigned type, >> always shifts in zeros.
constexpr std::uint32_t shift_right_logical(std::uint32_t x, int k) {
    return x >> k;
}
 
// The same bits read as a signed two's-complement value. Since C++20 the
// conversion of an out-of-range unsigned value to a signed type is modular and
// >> on a negative value is arithmetic; before C++20 both were implementation-defined.
constexpr std::int32_t to_signed(std::uint32_t x, int width) {
    return static_cast<std::int32_t>(x << (32 - width)) >> (32 - width);
}
 
// Arithmetic: copies of the sign bit come in.
constexpr std::uint32_t shift_right_arithmetic(std::uint32_t x, int k, int width) {
    return static_cast<std::uint32_t>(to_signed(x, width) >> k) & mask(width);
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/bit_ops.hpp

References