> BitOps
Enter an integer : 30
30 is even
Enter an integer and a bit number : 30 6
30 has bit 6 off
Enter an integer, start and end bit numbers : 30 4 6
30 has not all those bits on
Example Parameters:
Start index (S) = 4, end index (E) = 6
Index : 8 7 6 5 4 3 2 1 0
30 in binary: 0 0 0 0 1 1 1 1 0
Mask: 0 0 1 1 1 0 0 0 0
We want to find the value of a mask such that when that value is converted
to binary, all the digits from start (S) to end (E) are one’s. Then we can
compare our mask to the original number (X).
In this example, X = 30, S = 4, E = 6.
The mask value in binary is 001110000
Converted to base 10, this is (2^6)+(2^5)+(2^4) = 64 + 32 + 16 = 112
After doing some math, I found that 2^(E+1) = 2^(6+1) = 128 and 2^(S) = 2^4 = 16
Furthermore, 2^(E+1) – 2^(S) = 128 – 16 = 112 (mask value)
So ( X & Mask ) compares the two values to see if all digits from S to E are on.
Remember:
0 & 0 = 0
1 & 0 = 0
1 & 1 = 1
30 in binary: 0 0 0 0 1 1 1 1 0
Mask: 0 0 1 1 1 0 0 0 0
Result (X & Mask): 0 0 0 0 1 0 0 0 0
We want the result to be zero, which would indicate that not all bits from the
starting digit (S = 4) to the ending digit (E = 6) are on. However, the problem
is that the result of the comparison returns a value that is not zero. The 5th digit
is a 1, which gives a value of 2^4 = 16. This non-zero result falsely suggests that
the bits from S to E are all on, when in fact they are not. So what do we do?




