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 and :
| 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 is , written 1 << k in C: a 1 at position and 0 everywhere else. With a mask :
test:
(x & m) != 0is true when any selected bit of is 1;set:
x | mmakes the selected bits 1;clear:
x & ~mmakes the selected bits 0;toggle:
x ^ mflips the selected bits;extract the field of bits that starts at position :
(x >> k) & ((1 << w) - 1)moves the field down to position 0 and then keeps only its bits.
Set, clear and toggle leave every bit outside the mask unchanged; test and extract ignore those bits.
Shifts. Let be the width of the word in bits. A left shift by moves every bit 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 and keeps the remainder modulo . 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 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 , so it acts as the sign bit, and an arithmetic right shift of a signed value divides by and rounds toward minus infinity.
Rotations. A rotation by 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 , a right rotation can be written (x >> r) | (x << (w - r)) on an unsigned -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 = 1101 0110 in binary, which is 0xD6, or .
Test bit 2 with mask
0000 0100:1101 0110AND0000 0100is0000 0100, which is not zero, so bit 2 is set.Clear bit 7: the complement of
1000 0000is0111 1111, and1101 0110AND0111 1111is0101 0110, which is .Set bit 0:
1101 0110OR0000 0001is1101 0111, which is 215.Toggle the low four bits twice with mask
0000 1111:1101 0110XOR0000 1111is1101 1001, and1101 1001XOR0000 1111is1101 0110again.Extract the 3-bit field in bits 2 to 4: shifting right by 2 gives
0011 0101, which is 53, the same as rounded down; AND with0000 0111keeps101, which is 5, the same as .
Now move = 1101 0101, which is 213, by 2 positions.
Left shift:
0101 0100, which is 84; indeed , and .Logical right shift:
0011 0101, which is 53, and rounded down is 53.Arithmetic right shift:
1111 0101. Read as 8-bit two’s-complement numbers, is and the result is ; , rounded toward minus infinity, is .Right rotation:
0111 0101, which is 117. The two bits that leave the bottom,01, re-enter at the top. By the formula, , the two low bits move up to weight , and .
The three right moves give three different answers from the same bits.
Stated precisely
Write a -bit word as , with each bit equal to 0 or 1. Let denote XOR and denote NOT. For every position : Hence as an unsigned number. For a shift amount with , write for the left shift and for the logical right shift: where is rounded down. The arithmetic right shift gives , written back in bits, where is the two’s-complement value of . For , the right rotation is and .
XOR is associative and commutative, and . Therefore for every and .
In C11 these formulas hold for unsigned operands after integer promotion §4.18, with the width of the promoted type, provided the shift count is at least 0 and less than ; 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 , 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: shifted arithmetically right by 2 is , but -43 / 4 is .
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 and are masked with the same , then : an observer of both results learns how the two messages differ, without knowing .
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, for any mask , and , so , where 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 and masked with the same , the XOR of the two results is , 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 , not 0xF0.
Is right shift always unsigned division by two?
No. A logical right shift of an unsigned value by positions, which fills the vacated high bits with 0, equals division by rounded down: 213 shifted right by 2 is 53, since . 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: shifted arithmetically right by 2 is , while C’s integer division -43 / 4 gives , 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].