Can some one explain how it's get the first and second bit, so, how is (i&2)/2 getting the second bit ? for(i=0; i < 4; i++) { bit_a = (i & 2) / 2; // Get the second bit. bit_b = (i & 1); // Get the first bit. printf("%d | %d = %d\n", bit_a, bit_b, bit_a | bit_b); }
bit_a=(i&2)/2; This instruction can be written in C also(it's more appropriate to write it that way): bit_a=(i&2)>>2; Now at first iteration i=0: i= 0000 0000 2= 0000 0010 -----&------- i&2=0000 0000 2= 0000 0010 ----->>------ bit_a=0000 0000//The second bit.You can't see it because it's equal to the first one=0 i= 0000 0000 1= 0000 0001 -----&-------- bit_b=0000 0000//The first bit.You can't see it because it's equal to the first one=0 now in printf you got bit_a|bit_b=0000 0000 Now at second iteration i=1: i= 0000 0001 2= 0000 0010 -----&------- i&2=0000 0000 2= 0000 0010 ----->>------ bit_a=0000 0000//The second bit pushed on the first position division with 2. i= 0000 0001 1= 0000 0001 -----&-------- bit_b=0000 0001//The first bit. now in printf you got bit_a|bit_b=0000 0001 . . REVIEW BIT'S OPERATIONS CHAPTER I HOPE YOU GOT IT!
Let's just consider three bit numbers. ``` 0 000 1 001 2 010 3 011 4 100 5 101 6 110 7 111 ``` Some things should be coming clear now. 1 is the first bit `001` 2 is the second bit `010` 4 is the third bit `100` Notice how 3 is `011` and 6 is `110` Each time you multiply by 2, you shift everything to the left. There is actually an operator in C that lets you shift everything to the left multiple times. It's the `<<` operator. So `1 << 2` takes `1=001` shifts it `2` times so it becomes `100=4`. In general, `x << n` is a very fast way to calculate \(x \cdot 2^n\). An even easier way to get the nth bit would be to use the left shift operator. `(x >> (n -1)) & 1` will give you the nth bit. Let's disect it. Suppose you have `7=111`. If you want the second bit, first it will do `n-1` which evaluates to 1. This means shift right once. We would shift 0 times for the first bit because it is already the right most bit. So it will do `111 >> 1` which will give us `011`. Next thing is the ` & 1`. This operation will and each bit together. So we have `011 & 001` which results in `001`. Consider if you want the second bit of 5. Here is how it will work: ``` (5 >> (2 - 1)) & 1 (5 >> 1) & 1 // 5 = 101, 010 = 6 2 & 1 // 010 & 001 = 000 0 ``` So the second bit of 5 doesn't exist, and we get 0.
Join our real-time social learning platform and learn together with your friends!