Section 4.50

Bit operations: truth tables, masks, shifts, and rotations

Definition

Bit operations are operations on the individual bits of fixed-width words. The bitwise operations AND, OR, XOR (exclusive OR) and NOT apply a truth table, which lists the output for each combination of input bits, separately at each bit position. A shift moves all bits left or right by a number of positions and drops those that move past the end; a rotation moves them likewise but brings the dropped bits back in at the other end. A mask is a word whose 1 bits mark the positions to affect.

The idea

A hardware control register packs many settings into one 32-bit word: bit 0 might switch a peripheral on, bit 1 enable its interrupt §6.11, and bits 4 to 6 select one of eight modes. Software must test, set or clear one setting without disturbing the others, and must read the 3-bit mode out as a number. Ordinary arithmetic is a poor tool for this, because a carry from one position spills into the next. Bit operations treat each position on its own, which is exactly what packed settings need.

Picture the word as a row of light switches and a mask as a stencil with holes over some of them. OR with the mask turns on every switch under a hole. AND with the complement of the mask turns off every switch under a hole. XOR with the mask flips every switch under a hole. AND with the mask hides every switch that is not under a hole, so only the selected ones can be read. Shifts and rotations slide the whole row along. The picture stops at the ends of the row: what happens there depends on the width of the word and on the operation, and that is where most mistakes are made.

How it works

Truth tables. For one bit position with inputs aa and bb:

aa bb AND OR XOR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

AND is 1 only when both inputs are 1. OR is 1 when at least one input is 1. XOR is 1 when exactly one input is 1, so it differs from OR only when both inputs are 1. NOT, also called the complement, turns each 0 into 1 and each 1 into 0. In C the four operators are &, |, ^ and ~.

Masks. Number the bit positions from 0 at the least significant end, the right-hand end when the word is written out. The mask for position kk is 2k2^k, written 1 << k in C: a 1 at position kk and 0 everywhere else. With a mask mm:

Set, clear and toggle leave every bit outside the mask unchanged; test and extract ignore those bits.

Shifts. Let ww be the width of the word in bits. A left shift by kk moves every bit kk positions toward the most significant end, fills the vacated low positions with 0 and drops the bits pushed past the top. For an unsigned word this multiplies by 2k2^k and keeps the remainder modulo 2w2^w. A logical right shift moves every bit toward the least significant end, fills the vacated high positions with 0 and drops the bits pushed past position 0. For an unsigned word this divides by 2k2^k and rounds down. An arithmetic right shift fills the vacated high positions with copies of the top bit. In two’s complement, the usual encoding of signed integers, the top bit has weight −2w−1-2^{w-1}, so it acts as the sign bit, and an arithmetic right shift of a signed value divides by 2k2^k and rounds toward minus infinity.

Rotations. A rotation by rr positions moves bits like a shift but feeds the bits that leave one end back in at the other end, so no bit is lost. For 0<r<w0 < r < w, a right rotation can be written (x >> r) | (x << (w - r)) on an unsigned ww-bit word. Many processors have a rotate instruction. C has no rotate operator; the expression above is the usual way to write one, and compilers turn it into a rotate instruction where one exists.

Worked example

Take the 8-bit register value xx = 1101 0110 in binary, which is 0xD6, or 128+64+16+4+2=214128 + 64 + 16 + 4 + 2 = 214.

Now move yy = 1101 0101, which is 213, by 2 positions.

The three right moves give three different answers from the same bits.

Stated precisely

Write a ww-bit word as x=∑i=0w−1xi2ix = \sum_{i=0}^{w-1} x_i 2^i, with each bit xix_i equal to 0 or 1. Let ⊕\oplus denote XOR and ¬\lnot denote NOT. For every position ii: (x&y)i=xiyi,(x|y)i=xi+yi−xiyi,(x⊕y)i=(xi+yi)mod2,(¬x)i=1−xi.(x \mathbin{\&} y)_i = x_i y_i, \quad (x \mathbin{|} y)_i = x_i + y_i - x_i y_i, \quad (x \oplus y)_i = (x_i + y_i) \bmod 2, \quad (\lnot x)_i = 1 - x_i. Hence ¬x=2w−1−x\lnot x = 2^w - 1 - x as an unsigned number. For a shift amount kk with 0≤k<w0 \le k < w, write x≪kx \ll k for the left shift and x≫kx \gg k for the logical right shift: x≪k=(x⋅2k)mod2w,x≫k=⌊x/2k⌋,x \ll k = (x \cdot 2^k) \bmod 2^w, \qquad x \gg k = \lfloor x / 2^k \rfloor, where ⌊z⌋\lfloor z \rfloor is zz rounded down. The arithmetic right shift gives ⌊σ(x)/2k⌋\lfloor \sigma(x) / 2^k \rfloor, written back in ww bits, where σ(x)=x−2wxw−1\sigma(x) = x - 2^w x_{w-1} is the two’s-complement value of xx. For 0<r<w0 < r < w, the right rotation is rotr(x,r)=⌊x/2r⌋+(xmod2r)⋅2w−r,\mathrm{rotr}(x, r) = \lfloor x / 2^r \rfloor + (x \bmod 2^r) \cdot 2^{w - r}, and rotr(x,0)=x\mathrm{rotr}(x, 0) = x.

XOR is associative and commutative, m⊕m=0m \oplus m = 0 and x⊕0=xx \oplus 0 = x. Therefore (x⊕m)⊕m=x⊕(m⊕m)=x(x \oplus m) \oplus m = x \oplus (m \oplus m) = x for every xx and mm.

In C11 these formulas hold for unsigned operands after integer promotion §4.18, with ww the width of the promoted type, provided the shift count is at least 0 and less than ww; any other count is undefined behavior §4.12. For signed operands, C11 makes a right shift of a negative value implementation-defined, and a left shift of a negative value, or one whose result does not fit, undefined.

Limits and common mistakes

The width is part of the operation. In C, an operand narrower than int is first converted to int, which is integer promotion. With uint8_t x = 0x0F; and a 32-bit int, the expression ~x is the int value −16-16, bit pattern 0xFFFFFFF0, not 0xF0, so ~x == 0xF0 is false. Convert or mask the result back to 8 bits before comparing.

Operator precedence in C is a trap: == binds more tightly than &, so x & m == 0 means x & (m == 0). Write (x & m) == 0.

Bitwise is not logical. 1 & 2 is 0, because the two values share no bit, while 1 && 2 is 1, because both values are nonzero; && also skips its right operand when the left one is 0.

Right shift is not always division. An arithmetic right shift of a negative value rounds toward minus infinity, while C’s / rounds toward zero: −43-43 shifted arithmetically right by 2 is −11-11, but -43 / 4 is −10-10.

Shift counts at or beyond the width behave differently on different processors, which is why C leaves them undefined. For a 32-bit shift by a count in a register, x86 processors use only the low 5 bits of the count, so a shift by 32 leaves the value unchanged; 32-bit Arm uses the low byte of the count, so a shift by 32 gives 0. The Shift semantics §4.20 entry gives the full C rules.

A read-modify-write is not atomic. reg |= m reads reg, ORs in the mask and writes the result back, and another writer that acts between the read and the write loses its change. An atomic operation §9.8, a short section with interrupts disabled, or hardware with separate set and clear registers avoids this.

XOR masking is reversible, not secret. If two messages p1p_1 and p2p_2 are masked with the same kk, then (p1⊕k)⊕(p2⊕k)=p1⊕p2(p_1 \oplus k) \oplus (p_2 \oplus k) = p_1 \oplus p_2: an observer of both results learns how the two messages differ, without knowing kk.

Questions answered

Why does XOR with the same mask twice restore the value?

XOR (exclusive OR) with a 1 bit flips a bit and XOR with a 0 bit leaves it unchanged, so applying the same mask twice flips each selected bit twice, which returns it to its starting value, and never touches the other bits. Algebraically, XOR is associative, m⊕m=0m \oplus m = 0 for any mask mm, and x⊕0=xx \oplus 0 = x, so (x⊕m)⊕m=x⊕(m⊕m)=x⊕0=x(x \oplus m) \oplus m = x \oplus (m \oplus m) = x \oplus 0 = x, where ⊕\oplus denotes XOR. With 8-bit values: 1101 0110 XOR 0000 1111 is 1101 1001, and 1101 1001 XOR 0000 1111 is 1101 0110 again.

This is why a stream cipher, which encrypts by XOR with a secret sequence of pseudorandom bits, decrypts with the same operation. It is also why reusing the sequence is dangerous: for two messages p1p_1 and p2p_2 masked with the same kk, the XOR of the two results is p1⊕p2p_1 \oplus p_2, with the mask gone.

Why must a complement or rotation specify its width?

Both operations involve every position of the word, and the number of positions is the width. A complement (bitwise NOT) flips every bit, so the 4-bit complement of 0101 is 1010 (10), while the 8-bit complement of 0000 0101 is 1111 1010 (250): the extra high bits become 1. A rotation feeds the bits that leave one end back in at the other end, so the width decides where they re-enter: rotating 0001 right by one gives 1000 (8) in 4 bits but 1000 0000 (128) in 8 bits. In C, an operand narrower than int is promoted to int before the operation, so the width is usually 32 bits even when the variable is 8 bits wide: for an 8-bit x equal to 0x0F, ~x is the int value −16-16, not 0xF0.

Is right shift always unsigned division by two?

No. A logical right shift of an unsigned value by kk positions, which fills the vacated high bits with 0, equals division by 2k2^k rounded down: 213 shifted right by 2 is 53, since 213/4=53.25213 / 4 = 53.25. An arithmetic right shift instead copies the sign bit into the vacated positions, and for a negative two’s-complement value it equals division rounded toward minus infinity: −43-43 shifted arithmetically right by 2 is −11-11, while C’s integer division -43 / 4 gives −10-10, because C division rounds toward zero. In C, right-shifting a negative signed value is implementation-defined (mainstream compilers perform an arithmetic shift), and a shift by a negative count, or by at least the width of the promoted operand, is undefined behavior.

Does setting a bit with a mask make a concurrent update safe?

No. x |= m is three steps: read x, OR in the mask, write x back, and another writer can act between the read and the write. For example, x is 0000 0000, and the main program reads it to set bit 0. An interrupt handler §6.12 then sets bit 1, making x equal to 0000 0010. The main program writes back its result, 0000 0001, and bit 1 is lost. The mask arithmetic is correct; the sequence is not atomic. The update becomes safe with an atomic read-modify-write instruction or library function, such as C11’s atomic_fetch_or; with interrupts disabled around the update on a single-core microcontroller §6.1; or with a peripheral’s separate set and clear registers, which change only the bits written as 1.

Related entries: Signed versus unsigned comparison (§2.12), Integer promotion and conversion (§4.18), Modified immediate encoding (§4.43), Bitmask abstract value (tnum) (§3.10), Opcode (§2.8), Happens-before relation (§9.10), Shift semantics (§4.20), Atomic operation (§9.8), Boolean algebra and De Morgan laws (§15.39). Further reading: [78, 198].