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 & −xisolates 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&, sox & 1 == 0meansx & (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 << 31in Java or C# is negative, and1 << 32is 1; in C++1 << 31on a 32-bitintwas undefined in C++11 (C++14 and C++17 made it implementation-defined; only C++20 fully defines it). Write1u << ior1L << ias needed.- Assuming Python ints wrap. They never do; without a mask,
x << 1just 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) & 1reads one. x & (x − 1)clears the lowest 1,x & −xisolates 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.