I'm preparing for an interview using the text, "Cracking the Coding Interview" by Gayle Laakman McDowell. On the section covering bit manipulation, there are two functions that are provided, but I don't quite understand how it works.
// To clear all bits from the most significant bit through i (inclusive), we do:
int clearMSBthroughI(int num, int i) {
int mask = (1 << i) - 1;
return num & mask;
}
// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
int mask = ~(((1 << (i+1)) - 1);
return num & mask;
}
In the first function, I understand what (1 << i)
does of course, but what I'm not sure of is how subtracting 1 from this value affects the bits (i.e., (1 << i) - 1)
).
I basically have the same confusion with the second function. To what effects, specifically on the bits, does subtracting 1 from ((1 << (i+1))
have? From my understanding, ((1 << (i+1))
results in a single "on" bit, shifted to the left i+1 times--what does subtracting this by 1 do?
Thanks and I hope this was clear! Please let me know if there are any other questions.
For those who by some chance have the text I'm referencing, it's on page 91 in the 5th Edition.