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!
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!
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;
.|
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
The |= 1ULL << i
simply means set the i
th 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
.
It's left shifting 1 by i places, and OR'ing the result with n. Effectively it's setting bit i in n.
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..
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.