Rounding down/up to nearest power of 2

Revision en3, by HemanSeervi, 2025-01-26 08:14:48

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

Tags bitmask, bitmanipulation, binary numbers

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English HemanSeervi 2025-01-26 08:14:48 129
en2 English HemanSeervi 2025-01-26 08:13:54 2 Tiny change: 'Source : Hacker's Delight\n\n\n\nTu' -> '_Source : Hacker's Delight_\n\n\n\nTu'
en1 English HemanSeervi 2025-01-26 08:13:13 1151 Initial revision (published)