HemanSeervi's blog

By HemanSeervi, history, 23 hours ago, In English

Source : Hacker's Delight

Turn on all of the bits after MSB

This trick propogates MSB to all of the positions to the right of it 00110010 -> 00111111 00010011 -> 00011111 01000000 -> 01111111

x |= x>>1;
x |= x>>2;
x |= x>>4;
x |= x>>8;
x |= x>>16;

It works for 32 bit integers (How to modify for 64 bit?)

Round Down

x |= x>>1;
x |= x>>2;
x |= x>>4;
x |= x>>8;
x |= x>>16;
x = (x>>1) + 1

this gives 1 for rounding down 0 to a power of 2. But as rounding down 0 doesnt make sense for 2^x is always > 0, this can be considered a case of invalid input

Round Up

x--;
x |= x>>1;
x |= x>>2;
x |= x>>4;
x |= x>>8;
x |= x>>16;
x++;

x--; is just an adjustment for : if the value is already a power of 2 we want the same number back (ceil of log2(x-1)), if we need strictly the next power of 2 x--; should be removed

  • Vote: I like it
  • +3
  • Vote: I do not like it