Bit Manipulation: Power of Bits

Apply masks, shifts, and popcount patterns safely. Learn how integer width, signedness, language rules, and overflow affect bit operations.

published: reading time: 19 min read author: Geek Workbench updated: November 6, 2026
Quick Summary

Bit operations help set flags, isolate values, test powers of two, and count set bits. Shift operations act like multiplication or division only under the width, signedness, overflow, and language rules of the integer type. Fixed-width examples make those boundaries clear, while masks and popcount patterns remain useful when they improve clarity.

Bit Manipulation: Power of Bits

Bit manipulation operates directly on an integer’s bits to set flags, isolate values, and count set bits. Shift operations can resemble multiplication or division, but their results depend on width, signedness, overflow, and language rules.

For the gate-level logic behind these operators, see Boolean Logic & Gates. To see how bit operations fit into a processor, continue with the CPU simulator, Instruction Set Architecture, and Assembly Language Basics.

When to Use

Bit manipulation shines when:

  • Space is at a premium — Flags, bitmaps, and compact encodings save memory
  • Arithmetic constraints — In fixed-width code, shifts can replace multiplication or division by powers of two when the signedness, overflow, and rounding behavior match the task
  • Finding unique element — XOR identifies the element appearing once among pairs
  • Bit counting — Hamming weight problems for parity or similarity measures
  • Power of 2 checks — Single bit means exactly one set bit

When Not to Use

  • When readability matters more than optimization (bit hacks can obscure intent)
  • Languages without unsigned integers or with platform-dependent shift behavior
  • When standard library functions already solve the problem clearly

Core Operations Reference

Operation Symbol Truth Table Common Use
AND & 1&1=1, else 0 Clear bits, isolate masks
OR | 0|0=0, else 1 Set bits
XOR ^ 1^1=0, 0^0=0, else 1 Toggle, find unique
NOT ~ Flips all bits Two’s complement math
Left Shift << Moves bits left; arithmetic equivalence depends on width and overflow Masks or scaling under stated rules
Right Shift >> Sign or zero extension depends on type and language Extract bits or scale under stated rules

Shift Semantics: Width, Signedness, and Language

For a fixed-width value of w bits and a shift distance k with 0 <= k < w, a left shift moves the bit pattern toward the high end. It equals multiplication by 2^k only when the mathematical result fits, or when the language explicitly defines the overflow result you want. Signed and unsigned right shifts may fill vacated bits differently, and some languages mask shift distances instead of rejecting out-of-range values.

Java makes these rules explicit: int shifts use 32-bit values and long shifts use 64-bit values. << discards bits shifted out of that width; >> sign-extends and rounds negative values down; >>> fills with zeroes. Java uses only the low five bits of an int shift distance and the low six bits of a long shift distance (Java SE 26 JLS §15.19). For example:

int scaled = 3 << 2;                   // 12
int wrapped = 0x40000000 << 1;         // 0x80000000, or -2147483648
int arithmetic = -9 >> 1;              // -5 (floor division)
int logical = -9 >>> 1;                // 0x7ffffffb, or 2147483643
int maskedIntDistance = 1 << 32;       // 1: 32 & 31 is 0
long maskedLongDistance = 1L << 64;    // 1: 64 & 63 is 0

Save this as ShiftSemanticsTest.java, compile with javac ShiftSemanticsTest.java, then run java -ea ShiftSemanticsTest to check the expected results:

public class ShiftSemanticsTest {
    public static void main(String[] args) {
        assert (3 << 2) == 12;
        assert (0x40000000 << 1) == Integer.MIN_VALUE;
        assert (-9 >> 1) == -5;
        assert (-9 >>> 1) == 2147483643;
        assert (1 << 32) == 1;
        assert (1L << 64) == 1L;
    }
}

Python integers have arbitrary precision, so 1 << 40 is 1099511627776 rather than a 32-bit wrapped value; negative >> is arithmetic. C and C++ signed-shift rules also differ from Java and depend on the language standard. When the task is about a bit pattern, use an explicitly sized unsigned type where available and state the width.

Production Failure Scenarios

Failure Cause Mitigation
Shift assumptions Width, signedness, overflow, and shift-count rules differ by language Check the target type and language version; use explicit-width examples
Off-by-one in bit isolation Confusing 1-indexed vs 0-indexed bit positions Draw binary representation explicitly
NOT vs negative numbers ~x = -x - 1 in two’s complement catches everyone off guard Always test with edge cases like 0, 1, -1
JavaScript bit operations Number bitwise operators coerce operands to 32-bit values Use >>> 0 when an unsigned 32-bit result is intended

Trade-off Table

Approach Operation Count Readability Performance
Arithmetic 1 High Slower on older hardware
Bit shift 1 Medium Not guaranteed faster than arithmetic
Lookup table 1 High Fastest but uses memory
Modular arithmetic Multiple Medium Variable

For most modern code, readability wins. If you’re writing crypto or low-level systems code, the bit tricks matter more.

Implementation

Bitwise Operations Reference

These examples cover common bit problems, from masks and power-of-two checks to Hamming weight, range AND, and finding a unique element with XOR cancellation. The implementations use Python integers; when porting to a fixed-width language, account for that type’s width, signedness, and overflow rules. XOR swap appears only as an interview curiosity, not as a recommended way to exchange values.

Reference: Bitwise Operations Reference

XOR Swap (Interview Curiosity)

This algebraic trick is shorter than it looks only on paper. In languages where two operands can refer to the same storage, aliasing makes the first XOR clear that value; the sequence is also harder to read than a temporary or built-in swap. Keep it as an interview exercise, not production advice.

def swap(a, b):
    """
    Demonstrate XOR cancellation; prefer a normal swap in application code.
    """
    a = a ^ b
    b = a ^ b  # b = (a ^ b) ^ b = a
    a = a ^ b  # a = (a ^ b) ^ a = b
    return a, b

Check if Number is Power of 2

def is_power_of_two(n):
    """
    Power of 2 has exactly one set bit.
    n & (n-1) clears the lowest set bit.
    If result is 0, exactly one bit was set.
    """
    return n > 0 and (n & (n - 1)) == 0

Count Set Bits (Hamming Weight)

def count_bits(n):
    """
    Count set bits using Brian-Kernighan algorithm.
    """
    count = 0
    while n:
        n &= (n - 1)  # Clear lowest set bit
        count += 1
    return count

Find Single Element in Array of Pairs

def find_single(nums):
    """
    XOR all elements. Pairs cancel out to 0, singles remain.
    """
    result = 0
    for num in nums:
        result ^= num
    return result

Bitwise AND Range [m, n]

def range_bitwise_and(m, n):
    """
    Find AND of all numbers from m to n.
    The answer is the common prefix of m and n.
    """
    shift = 0
    while m != n:
        m >>= 1
        n >>= 1
        shift += 1
    return m << shift

Power of Two Check Alternative

def is_power_of_two_v2(n):
    """
    Using n & (-n) isolates the lowest set bit.
    Power of 2 has only one set bit, so n & (-n) == n.
    """
    return n > 0 and (n & (-n)) == n

Common Pitfalls / Anti-Patterns

  1. Confusing XOR with addition — XOR adds without carry; 1 ^ 1 = 0, not 2. This trips people up every time.
  2. Off-by-one in bit ranges — The bit at position 0 is the least significant (2^0=1). Always draw it out.
  3. Signed shifts across languages — Right-shift and overflow rules vary by language and version; use explicit-width types and check the relevant specification.
  4. JavaScript quirks — Number bitwise operators coerce operands to 32-bit values. Use >>> 0 when an unsigned 32-bit result is intended.
  5. Shift overflow — Bits shifted past a fixed-width type’s boundary do not behave like unbounded arithmetic; the result depends on language and signedness.

Quick Recap Checklist

  • XOR properties: a^a=0, a^0=a, a^b=b^a
  • n & (n-1) clears lowest set bit
  • n & (-n) isolates lowest set bit
  • Shift behavior checked for the type’s width, signedness, language, and overflow rules
  • Two’s complement: ~x = -x - 1

Interview Questions

1. How does n & (n-1) clear the lowest set bit?

In binary, n-1 flips all bits from the lowest set bit downward. For n = 1000 (8), n-1 = 0111 (7). The AND operation clears the lowest set bit: 1000 & 0111 = 0000. This property makes counting set bits and checking power-of-two very efficient.

2. How does the XOR-swap interview trick work, and why is it usually avoided?

Applying XOR three times exchanges two distinct values because a ^ a ^ b = b. It is not a good application-code pattern: if two operands alias the same storage, the first XOR clears it, and the sequence is harder to read than a temporary or built-in swap.

3. How do you find the two numbers that appear once while all others appear twice?

XOR all elements to get x ^ y where x and y are the unique numbers. Find any set bit in this result (e.g., x ^ y & -(x ^ y)). Partition numbers by whether that bit is set, XOR each partition separately. The partitions separate x and y because they differ on that bit, while pairs cancel within their partition.

4. When does shifting match multiplication or division?

For an in-range shift of a fixed-width value, left shift resembles multiplication by 2ⁿ only when the result fits or the language defines the overflow behavior you intend. Right shift depends on signedness and language: Java >> sign-extends and floors negative values, while >>> zero-fills. Check the type and language before relying on a shift as arithmetic.

5. How do you check if a number is a power of 4?

A power of 4 has exactly one set bit located at an even position (0-indexed). Check n > 0 && (n & (n - 1)) == 0 (power of 2) AND (n & 0xAAAAAAAAAAAAAAAA) == 0 (no set bits at odd positions). Alternatively, check n % 3 == 1 since powers of 4 modulo 3 always equal 1.

6. Explain the SWAR (SIMD Within a Register) technique for popcount.

SWAR computes popcount in O(log n) without branches by treating the register as packed SIMD lanes. Steps:

  • Pairwise sum adjacent bits using mask 0x55555555
  • Sum adjacent pairs with mask 0x33333333
  • Sum adjacent nibbles with mask 0x0F0F0F0F
  • Multiply by 0x01010101 or continue summing bytes/words
7. How would you add two integers without using the + or - operators?

Use bitwise XOR and AND with left shift in a loop:

  • XOR (^) computes the sum without carry
  • AND (&) << 1 computes the carry bits shifted left
  • Repeat until carry is 0

This is how ALUs implement addition at the hardware level.

8. How can you compute the absolute value of an integer without branching?

Compute the sign bit as mask = x >> 31 (or x >>> 31 in JS). Then abs = (x + mask) ^ mask. This equals ~x + 1 (negation) when x is negative and identity when x is positive. This avoids pipeline-flushing conditional branches.

9. How do you check if two integers have opposite signs without using comparison operators?

XOR the sign bits: (a ^ b) < 0. If the result is negative, their sign bits differ (most significant bit is 1). This is a common trick in sorting networks and branchless comparisons where you need to avoid branches.

10. How do you find the position of the only set bit in a number?

Use log2(n & (-n)) to isolate the lowest set bit and compute its 0-indexed position. In C/C++:

  • ffs() — find first set (1-indexed)
  • __builtin_ctz() — count trailing zeros

Always verify the number is a power of 2 first if you expect only one set bit.

11. What is the XOR of all numbers from 1 to N? Derive the pattern.

The XOR from 1 to N follows a repeating 4-cycle pattern:

  • N % 4 == 0 → N
  • N % 4 == 1 → 1
  • N % 4 == 2 → N + 1
  • N % 4 == 3 → 0

This works because XOR is associative and pairs (i, i+1) cancel in predictable ways. It's used to find the missing number by XORing expected vs actual values.

12. How does two's complement work and why is ~x = -x - 1?

In two's complement, negative numbers are represented as the bitwise NOT plus 1: -x = ~x + 1. Rearranging gives ~x = -x - 1.

  • Adding a number and its two's complement yields zero (with overflow)
  • The MSB acts as a sign bit: 0 for positive, 1 for negative
  • Range is asymmetric: -2^(n-1) to 2^(n-1) - 1
13. How can you use bitmasks to represent and query sets of flags efficiently?

Assign each flag a distinct power of 2 (bit position). Combine with OR, test with AND:

  • Set flag: flags |= mask
  • Clear flag: flags &= ~mask
  • Toggle: flags ^= mask
  • Test: (flags & mask) != 0

This compresses up to 64 boolean flags into a single 64-bit integer, enabling constant-time operations and SIMD-friendly data structures.

14. How do you reverse the bits of an integer?

Use a divide-and-conquer swap approach (similar to SWAR):

  • Swap adjacent bits with mask 0x55555555
  • Swap adjacent bit pairs with mask 0x33333333
  • Swap adjacent nibbles with mask 0x0F0F0F0F
  • Swap bytes (16-bit chunks)

This runs in O(log n) operations. For 32-bit integers, this takes 5 steps. Alternatively, use a lookup table mapping bytes to their reversed form.

15. How do you find the missing number in an array of 0..n?

XOR all array elements with all numbers from 0 to n. Pairs cancel out (a^a=0), leaving only the missing number. This works in O(n) time and O(1) space without modifying the array, and avoids overflow that would occur with summation.

16. How can you check if a number has alternating bits?

XOR the number with itself shifted right by 1: (n ^ (n >> 1)). If the number has alternating bits, the result will be all 1s (like 0b111...). Then check if that result + 1 is a power of 2: (((n ^ (n >> 1)) + 1) & (n ^ (n >> 1))) == 0.

17. How does the Gray code work and how do you generate it?

A Gray code sequence has consecutive values differing by exactly one bit. The n-th Gray code is n ^ (n >> 1). Binary to Gray and Gray to binary conversion:

  • Binary → Gray: gray = bin ^ (bin >> 1)
  • Gray → Binary: bin = gray; while (gray >>= 1) bin ^= gray

Applications: Karnaugh maps, error correction, analog-to-digital converters.

18. How do arithmetic and logical right shifts differ?

An arithmetic shift copies the sign bit into the vacated positions; a logical shift fills them with zeros. In Java, >> is arithmetic and >>> is logical for both int and long. JavaScript uses 32-bit Number operands for bitwise operators, with >> arithmetic and >>> logical. Other languages and types may differ, so check their shift rules.

19. How do you count the number of bits to flip to convert integer A to integer B?

XOR A and B, then count the set bits in the result: popcount(A ^ B). Each set bit in the XOR indicates a position where A and B differ, requiring a flip. This is the Hamming distance between two integers and is used in error detection, cryptography, and similarity measures.

20. How do you determine if a number is a multiple of 2 without using the modulo operator?

Check the least significant bit: (n & 1) == 0. In binary, even numbers always end with 0 and odd numbers with 1. This is faster than modulo on some architectures and is the canonical way to check parity in performance-sensitive code.

Further Reading

Books & Articles

Hacker’s Delight collects low-level programming techniques with proofs and timing comparisons. Its chapter on population count covers methods from Brian Kernighan’s algorithm and SWAR to hardware intrinsics. The book focuses on practical code more than theory.

Matters Computational by Jörg Arndt covers bitwise algorithms in computational mathematics, including Gray codes, bit permutations, and number-theoretic transforms. It gives more mathematical detail than Hacker’s Delight and explains why these techniques work.

Bit Twiddling Hacks by Sean Eron Anderson began as a Stanford web page. The online collection is updated over time, and a book version contains the same material. Entries explain each operation and its bit-level reasoning, with timing notes where available. It works as a reference when you have a specific operation in mind.

Topic-Specific Deep Dives

The core section covers individual tricks, but interview problems often stack multiple patterns together or push them into specialized territory. What follows is a deeper look at four topics that come up constantly in harder problems: subset enumeration via bitmasks, popcount variations, Gray code, and the footguns around sign extension and endianness when you are working with raw binary data.

Subset Enumeration Using Bitmasks

Represent any subset of an N-element set as an N-bit integer where the i-th bit is 1 if element i is included. Iterating from 0 to 2^N - 1 enumerates all subsets in Gray-code order when using s = s & (s - 1) to visit only set bits. This is the foundation of DP over subsets (e.g., traveling salesman problem with bitmask DP).

# Enumerate all subsets of a set represented by bitmask
mask = 0b1101  # elements 0, 2, 3
sub = mask
while sub:
    # process subset 'sub'
    sub = (sub - 1) & mask

Popcount (Hamming Weight) Variations

Beyond Brian Kernighan’s algorithm, hardware intrinsics like POPCNT on x86 and __builtin_popcount() in GCC offer O(1) popcount. For software implementations, the parallel-prefix divide-and-conquer method (also called “SWAR” — SIMD within a register) runs in O(log n) without loops:

def popcount_swar(x):
    x = x - ((x >> 1) & 0x55555555)
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    x = (x + (x >> 4)) & 0x0F0F0F0F
    x = x + (x >> 8)
    x = x + (x >> 16)
    return x & 0x3F

Gray Code Generation

Gray codes ensure consecutive values differ by exactly one bit, useful for Karnaugh maps, error correction, and analog-to-digital converters. The n-th Gray code is computed as n ^ (n >> 1).

Sign Extension and Endianness

When extracting bitfields from network protocols or binary file formats, account for sign extension and endianness separately. Convert to an explicitly sized unsigned representation where available, keep shift distances within the width, and mask the extracted field; these steps make the intended bit pattern clear across platforms.

Online Resources

Bit Twiddling Hacks is the Stanford-hosted version of Anderson’s collection, updated more frequently than any printed reference. Bookmark it. The page is organized by operation type (counting bits, finding bits, reversing bits) with copy-pasteable code. Each trick has a brief explanation of the bit-level reasoning. If you encounter a bit manipulation problem you haven’t seen before, this is the first place to check.

LeetCode Bit Manipulation Tag groups interview problems by subtopic: single number, bit counting, reverse bits, bitwise AND of range, etc. The problems are drawn from real interviews at major tech companies. Working through the Medium problems in each subtopic is the fastest way to build intuition for interview-style bit manipulation. The forum discussions on each problem often reveal edge cases that the official solution skips.

Compiler Explorer (godbolt.org) lets you write bit manipulation code and see how it compiles to assembly on different architectures. This is invaluable for understanding whether your clever trick actually produces better machine code than the naive approach, and whether the compiler is vectorizing your popcount. Paste your C/C++/Rust bit hack on the left, select x86, ARM, or RISC-V on the right, and watch the assembly get generated in real time. For low-level performance work, this is more useful than any documentation.

Conclusion

Bit operations are useful for masks, power-of-two tests, and popcount patterns such as n & (n - 1) or XOR cancellation. Treat shifts as operations on a specific integer representation: width, signedness, language rules, and overflow determine whether they match multiplication or division. For JavaScript Number bitwise operators, account for their 32-bit coercion. Prefer standard library operations when they make the intent clearer.

Category

Related Posts

Binary Search Variants: Beyond Simple Lookup

Choose binary search for monotone predicates and ternary search for unimodal objectives. Learn lower bounds, rotated-array search, and termination invariants.

#binary-search #algorithms #searching

Common Coding Interview Patterns

Learn five coding interview patterns, derive constraints before choosing one, and practice each with a recognition problem, variation, and mixed exercise.

#coding-interview #problem-solving #patterns

Sliding Window: Dynamic Subarray Problems

Solve maximum subarray, longest substring, and subarray average problems with O(n) time using the sliding window technique.

#sliding-window #algorithms #data-structures