In fact, an int is usually 32 bits. But I just put 16 bits in the comment to make it more understandable.
int i = 0; //00000000 00000000 int mask = 65536; //10000000 00000000 int retVal = 0; //00000000 00000000 int yourAmountOfBitsToOne = 2; for(i = 0; i < yourAmountOfBitsToOne; i++){ retVal = retVal | (mask >> i); } printf("%d", retVal);
If you run this, the output should be 216 + 215 = 98304.
Why?
Iteration 0:
line 1: retVal = 00000000 00000000 | (10000000 00000000 >> 0) line 1: retVal = 10000000 00000000
Iteration 1:
line 1: retVal = 10000000 00000000 | (10000000 00000000 >> 0) line 1: retVal = 10000000 00000000 | (01000000 00000000) line 1: retVal = 11000000 00000000
After completion is complete, you print an integer value of 11000000 00000000 , which is 98304 .
Create a function that prints int retVal differently, this will make it easier to verify that the output is correct. And this is also a very good exercise for learning bitwise operators.
Hope this helps.
source share