Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int setBitNumber(int n)
- {
- // Below steps set bits after MSB (including MSB)
- // Suppose n is 273 (binary is 100010001). It does following
- // 100010001 | 010001000 = 110011001
- // That is, the leftmost 2 bits will be set
- n |= n>>1;
- // This makes sure 4 bits
- // (From MSB and including MSB)
- // are set. It does following
- // 110011001 | 001100110 = 111111111
- // That is, the leftmost 4 bits will be set
- // (In previous step, we have set the leftmost 2 bits already)
- n |= n>>2;
- n |= n>>4; // Similarly, the leftmost 8 bits will be set
- n |= n>>8; // Similarly, the leftmost 16 bits will be set
- n |= n>>16; // Similarly, the leftmost 32 bits will be set
- // Increment n by 1 so that
- // there is only one set bit
- // which is just before original
- // MSB. n now becomes 1000000000
- // Note: only work for 2's complement numbering
- n = n + 1;
- // Return original MSB after shifting.
- // n now becomes 100000000
- // Notice: this may result in undefined behavior on signed integer
- return (n >> 1);
- }
- // Driver code
- int main()
- {
- setBitNumber(273)
- return 0;
- }
Add Comment
Please, Sign In to add comment