Confusion with bitwise operations | and <<

bit-manipulation, c

Solution

That line sets the ith bit of n.

- `1ULL` is the integer 1 with type unsigned long long.

- `<<` is a bitshift operator. `1ULL << i` is equal to 2i, or in binary: `100...0` with i zeros.

- `n |= x;` is a compound assignment operator. It is similar to writing `n = n | x;`.

- The operator `|` is the bitwise OR operator.

Wikipedia has an example showing how bitwise OR operator works in the general case:

   0101 (decimal 5)
OR 0011 (decimal 3)
 = 0111 (decimal 7)

Related

- What are bitwise shift (bit-shift) operators and how do they work?

- Bitwise operation

Problem

``` unsigned long long n = 0; for (int i = 0; i <= 64; i+=2) n |= 1ULL << i; //WHAT DOES THIS DO? AH! ``` I'm trying to wrap my head around what the third line of this code actually does. Someone please help clear this up!

Original source

Related problems