C/C++ Arena

Bitwise operators in C and C++

&, |, ^, ~, << and >> explained with examples: setting, clearing and testing bits, and bit flags.

Bitwise operators work on the individual bits of integers:

Operator Meaning Common use
a & b AND test or clear bits
a | b OR set bits
a ^ b XOR toggle bits
~a NOT flip every bit
a << n shift left multiply by 2 to the n; build masks
a >> n shift right divide by 2 to the n

Flags pack several yes/no options into one integer: flags |= FLAG sets one, flags &= ~FLAG clears it, and flags & FLAG tests it. Use unsigned types for bit work, since shifting negative numbers is not portable.

Example

#include <stdio.h>

#define CAN_READ  (1u << 0)
#define CAN_WRITE (1u << 1)

int main(void) {
    unsigned perms = 0;
    perms |= CAN_READ | CAN_WRITE;
    perms &= ~CAN_WRITE;
    printf("%d %d\n", (perms & CAN_READ) != 0, (perms & CAN_WRITE) != 0);
    return 0;
}

Output:

1 0

Practice it