Jordan
Jordan

Reputation: 2140

Confusion with bitwise operations | and <<

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!

Upvotes: 3

Views: 3211

Answers (5)

pdriegen
pdriegen

Reputation: 2039

it binary ORs n with the value 1 bit shifted by the value of i.

I believe the (binary) value of n would be:

0101010101010101010101010101010101010101010101010101010101010101

when the loop completed, although I haven't tested it..

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838276

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

Upvotes: 6

Donnie
Donnie

Reputation: 113

n |= 1ULL << i;       //WHAT DOES THIS DO? AH! 

On the right hand side you have "1ULL" which is a constant 1 unsigned long long. You are left bit shifting "1ULL" i number of times. The result of the left shifting of "1ULL" will then be matched with n to perform a bitwise OR. So n will be set to (n | (1ULL << i)).

This entire line or operation is setting the ith bit of n to a 1.

Upvotes: 1

peacemaker
peacemaker

Reputation: 2591

It's left shifting 1 by i places, and OR'ing the result with n. Effectively it's setting bit i in n.

Upvotes: 1

tskuzzy
tskuzzy

Reputation: 36466

The |= 1ULL << i simply means set the ith bit. The for loops over every second bit so every other bit in the 64 bit unsigned long long will be set to 1.

In other words, you will get a bit pattern like ...0101010101.

Upvotes: 1

Related Questions