Guest User

Untitled

a guest
Feb 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. int setBitNumber(int n)
  2. {
  3. // Below steps set bits after MSB (including MSB)
  4.  
  5. // Suppose n is 273 (binary is 100010001). It does following
  6. // 100010001 | 010001000 = 110011001
  7. // That is, the leftmost 2 bits will be set
  8. n |= n>>1;
  9.  
  10. // This makes sure 4 bits
  11. // (From MSB and including MSB)
  12. // are set. It does following
  13. // 110011001 | 001100110 = 111111111
  14. // That is, the leftmost 4 bits will be set
  15. // (In previous step, we have set the leftmost 2 bits already)
  16. n |= n>>2;
  17.  
  18. n |= n>>4; // Similarly, the leftmost 8 bits will be set
  19. n |= n>>8; // Similarly, the leftmost 16 bits will be set
  20. n |= n>>16; // Similarly, the leftmost 32 bits will be set
  21.  
  22. // Increment n by 1 so that
  23. // there is only one set bit
  24. // which is just before original
  25. // MSB. n now becomes 1000000000
  26. // Note: only work for 2's complement numbering
  27. n = n + 1;
  28.  
  29. // Return original MSB after shifting.
  30. // n now becomes 100000000
  31. // Notice: this may result in undefined behavior on signed integer
  32. return (n >> 1);
  33. }
  34.  
  35. // Driver code
  36. int main()
  37. {
  38. setBitNumber(273)
  39. return 0;
  40. }
Add Comment
Please, Sign In to add comment