Bitwise operators
suggest changeBitwise operators act on the promoted representations of integer operands:
| Operator | Meaning |
|---|---|
& |
bitwise AND |
| |
bitwise inclusive OR |
^ |
bitwise exclusive OR |
~ |
bitwise complement |
<< |
left shift |
>> |
right shift |
Use unsigned types for predictable bit manipulation:
#include <stdio.h>
int main(void)
{
unsigned a = 29; /* 0001 1101 */
unsigned b = 48; /* 0011 0000 */
printf("%u & %u = %u\n", a, b, a & b); /* 16 */
printf("%u | %u = %u\n", a, b, a | b); /* 61 */
printf("%u ^ %u = %u\n", a, b, a ^ b); /* 45 */
printf("~%u = %u\n", a, ~a);
printf("%u << 2 = %u\n", a, a << 2); /* 116 */
printf("%u >> 2 = %u\n", a, a >> 2); /* 7 */
}
The result of ~a depends on the width of unsigned, so no fixed decimal result is shown.
For a shift, the right operand must be nonnegative and less than the width of the promoted left operand; otherwise, behavior is undefined. Left-shifting an unsigned value discards high bits modulo one more than the maximum value. Left-shifting a signed nonnegative value is defined only when the result is representable. Right-shifting a negative signed value is implementation-defined.
Masks select or modify fields. This fragment assumes bool from C23 or from <stdbool.h>:
unsigned flags = 0;
flags |= 1u << 3; /* Set bit 3. */
flags &= ~(1u << 3); /* Clear bit 3. */
bool set = (flags & (1u << 3)) != 0;
Before shifting 1u, ensure that the requested bit index is less than the width of unsigned. Use a wider unsigned type when the field requires it.