Algorithm · Bits and math · O(1) per operation; popcount O(set bits)

Bit operations

Set, clear, toggle and test single bits, isolate the lowest set bit, count bits and shift, on a fixed-width integer with its two’s-complement reading.

The full derivation, edge cases and exercises are in the lesson Bits, masks and two’s complement. Open it full width in the playground.

On this page
  1. The idea
  2. Steps
  3. Invariants
  4. Complexity
  5. When to use it
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

An integer is a row of bits, and masks let you touch one of them: x | (1 << i) sets bit i, x & ~(1 << i) clears it, x ^ (1 << i) toggles it. Two identities do a lot of work: x & −x isolates the lowest set bit, and x & (x − 1) clears it, which counts the 1 bits in as many steps as there are.

Shifts differ by signedness: a logical right shift fills with zeros, an arithmetic one copies the sign bit. The languages disagree on which one >> means, which is a classic source of bugs.

Steps

  1. Build a mask with 1 << i.
  2. Combine it with x using |, & ~ or ^ to set, clear or toggle; test with (x >> i) & 1.
  3. Popcount: while x ≠ 0, x &= x − 1 and count.
  4. Reduce every result to the chosen width (8, 16 or 32 bits).

Invariants

What holds at every step; the correctness argument rests on these.

  • Results always fit the width (the value is masked after every operation).
  • Kernighan’s loop clears exactly one 1 bit per iteration.

Complexity

Bit operations complexity
CaseTimeExtra spaceNotes
Set / clear / toggle / test / shiftO(1)O(1)
Popcount (Kernighan)O(number of 1 bits)O(1)Hardware instructions do it in O(1).

When to use it

Use it when

  • Compact flag sets, masks over small sets (subsets as integers), parity and power-of-two checks.

Avoid it when

  • Readability matters more than a few bytes: a set or a few booleans is clearer.
  • Shifting by the width or more, or shifting negative values in C++ without knowing the rules.

Step through it

The interactive lab for bit operations: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

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

Learn more

Lessons

Problems, patterns and exercises

References