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

Bit operations

Masks, x & (x − 1) tricks, Kernighan popcount, two's complement and shifts on 8, 16 or 32 bits.

The full explanation, derivation and practice are in the lesson Bits, masks and two’s complement.

Implementation

The code the visualizer highlights, in four languages. Each is tested against one shared set of cases and a randomized comparison with the language's built-in equivalent.

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