To set 'N' bits in a number efficiently , N is a variable.
Interview Answers
Anonymous
Feb 16, 2012
Left shifting 1by N bits gives a power of 2 and if you subtract 1 from power of 2 you will N number of 1s.
1
Anonymous
Feb 7, 2012
MASK = (1 << N) - 1;
number = Number | MASK;
1
Anonymous
Feb 16, 2012
why -1?
Anonymous
Aug 25, 2012
This is wrong.
If u take the number 111 and if you want to set 4 bits, then there will be no
bits set at all. The total number of SET bits in 111 will remain unchanged.
Number 111 = 1101111(in bit representation)
Now 4 set bits = (1<<4)-1 = 15
Now OR these two numbers. 111 | 15
in bit representation 1101111
1111
-------------
1101111
-------------
So we can see that we haven't SET any bit additional.