Bit manipulation

Common use cases

Check odd/even number

boolean odd(int n) {
    return n & 0b1;
}

Half the number

int half(int n) {
    return n >> 1;
}

Double the number

int double(int n) {
    return n << 1;
}

Masking (opens in a new tab)

  • to 1: Y OR 1 = 1, Y OR 0 = Y
  • to 0: Y AND 0 = 0, Y AND 1 = Y

Masking bits to 1

  • OR target bits with 1s
  • OR unchanged bits with 0s

Masking bits to 0

  • AND target bits with 0s
  • AND unchanged bits with 1s

Querying the status of a bit

  • AND target bits with 1s
  • AND unwanted bits with 0s

Toggling bit values

  • XOR target bits with 1s
  • XOR unchanged bits with 0s

Reference