CodeBlanks Logo Icon CodeBlanks

Bitwise operators

Learn bitwise operations with &, |, ^, ~, << and >>.

Bitwise operators

Bitwise operators work on the binary bits of numbers: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift).

int a = 12;  /* 1100 */
int b = 10;  /* 1010 */
int c = a & b;  /* 1000 = 8 */
int d = a | b;  /* 1110 = 14 */

Bitwise AND gives 1 when both bits are 1. Bitwise OR gives 1 when at least one is 1. These operators are common in hardware and systems programming.

Shift operators

<< shifts bits left (multiplies by 2 each step), >> shifts right (divides by 2 each step).

int a = 5;
int b = a << 1;  /* 10: left 1, 5*2 */
int c = a >> 1;  /* 2: right 1, 5/2 */

Left shift is a fast multiply, right shift a fast divide. Right shift with negative numbers is compiler-dependent; watch for overflow.

Practice Print bitwise operation results

Define int a = 12, b = 10;. With five printf calls print a & b, a | b, a ^ b, a << 1 and a >> 1 on separate lines. Output should be 8, 14, 6, 24, 6.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int a = 12, b = 10;
    /* print a & b, a | b, a ^ b, a << 1, a >> 1 */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int a = 12, b = 10;
    printf("%d\n", a & b);
    printf("%d\n", a | b);
    printf("%d\n", a ^ b);
    printf("%d\n", a << 1);
    printf("%d\n", a >> 1);
    return 0;
}

Expected output

8
14
6
24
6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Bitwise AND operator

Question
int x = 12 ____ 10;  /* x = 8: bitwise AND */
Answer
int x = 12 & 10;  /* x = 8: bitwise AND */

Explanation: & is the bitwise AND operator.

2 Match bitwise operators

Term Meaning
& bitwise AND
| bitwise OR
^ bitwise XOR
~ bitwise NOT

3 Which is the bitwise AND operator?

  • & Correct answer
  • &&
  • +
  • and

Explanation: & is bitwise AND; && is logical AND.

All lessons in Beginner