+ 2
Need a little help in bitwise operators.
What does the following statement do? x=x|1<<n; Can anyone explain? Answer to this question is Sets (n+1)th bit of x why??? how??
3 Answers
+ 12
It's value depends on x and n. Precedence states it executes as follows:
x=(x|(1<<n));
so 1 is left shifted n bits, the result is ored with x, which is finally stored in x.
+ 15
Expanding on what John said, the expression shifts the positions of the binary bits n times to the left.
Using the reference below we see the first five binary bit positions read right to left:
16 | 8 | 4 | 2 | 1
Note the equivalent integer to binary conversions below:
1 => 00001 [ 0 + 0 + 0 + 0 + 1 ]
2 => 00010 [ 0 + 0 + 0 + 2 + 0 ]
3 => 00011 [ 0 + 0 + 0 + 2 + 1 ]
4 => 00100 [ 0 + 0 + 4 + 0 + 0 ]
5 => 00101 [ 0 + 0 + 4 + 0 + 1 ]
6 => 00110 [ 0 + 0 + 4 + 2 + 0 ]
7 => 00111 [ 0 + 0 + 4 + 2 + 1 ]
8 => 01000 [ 0 + 8 + 0 + 0 + 0 ]
9 => 01001 [ 0 + 8 + 0 + 0 + 1 ]
10 => 01010 [ 0 + 8 + 0 + 2 + 0 ]
11 => 01011 [ 0 + 8 + 0 + 2 + 1 ]
12 => 01100 [ 0 + 8 + 4 + 0 + 0 ]
Shifting bits involve moving the 1's from current bit positions by the specified number in the specified direction.
Examples:
-------------------------------------------------
Shifting 1 bit to the left.
-------------------------------------------------
1) 1 << 1
00001 => 00010
1 => 2
2) 2 << 1
00010 => 00100
2 => 4
3) 3 << 1
00100 => 01000
3 => 8
4) 4 << 1
01000 => 10000
4 => 16
-------------------------------------------------
Shifting 2 bits to the left.
-------------------------------------------------
5) 1 << 2
00001 => 00100
1 => 4
6) 2 << 2
00010 => 01000
2 => 8
7) 3 << 2
00011 => 01100
3 => 12
8) 4 << 2
00100 => 10000
4 => 16
-------------------------------------------------
Shifting 3 bits to the left.
-------------------------------------------------
9) 1 << 3
00001 => 01000
1 => 8
10) 2 << 3
00010 => 10000
2 => 16
I hope this makes sense. Cheers!
+ 4
@David , š , I better copy this post thread , it's not gonna be better than this , for the new ones