I have got a C program which does bitwise operations to get value of the bits. This is the program-
/*
* Example-
* BITS1|BITS2|BITS3|BITS4
* 0001| 0010| 0100| 1000
*
* 0001
* 0010
* 0100
* + 1000
* ------
* 1111
* ------------------------
* HOW TO GET VALUES WITH A LOOP?
*
* i = 1;
* 1111 << TOTAL-i
* =1000
*
* 1000 >> 3
* =1111 = VALUE OF FIRST BIT!
*
* i = 2;
* 1111 << TOTAL-i
* =1100
*
* 1100 >> 3
* =0001 = VALUE OF SECOND BIT!
*
* AND SO ON!!!
*/
#include <stdio.h>
typedef enum _bits_t {
BITS1 = 1,
BITS2 = 2,
BITS3 = 4,
BITS4 = 8
} bits_t;
int main() {
bits_t bits = BITS4|BITS1;
int i = 1, TOTAL = 4, current;
while(i <= TOTAL) {
current = ((bits<<(TOTAL-i))>>3)&1;
printf("value of bit %d = %d\n", i, current);
i++;
}
}
I put the comment at the start of the code to make me understand what to do and how. What I though was to do left shift on the number (to get rid of all bits in left), and then do right shift (to move the remaining bit to the right). I mean I calculated my current like this-
current = ((bits<<(TOTAL-i))>>3);
But to my surprise, that code didn't work. Then later on, just by luck, I put that &1 at the end of the line computing value of current, and then came a bigger surprise, that it worked! It computed the value of each bit correctly!.
But since it was just a blind guess, I don't currently understand why my program didn't work previously, and why does it now?
Please help me understand the program.
Thanks in advance.