Skip to content

Instantly share code, notes, and snippets.

@rygorous
Created May 21, 2014 21:12
Show Gist options
  • Save rygorous/64a2965486e4458c279f to your computer and use it in GitHub Desktop.
Save rygorous/64a2965486e4458c279f to your computer and use it in GitHub Desktop.
"Simple function to round up to the next power of 2"
//############################################################################
//## ##
//## Simple function to round up to the next power of 2. ##
//## ##
//############################################################################
static U32 Round_up_to_next_2_power( U32 value )
{
if ( value > 16 )
if ( value > 64 )
if ( value > 128 )
if ( value > 256 )
if ( value > 512 )
return( 1024 );
else
return( 512 );
else
return( 256 );
else
return( 128 );
else
if ( value > 32 )
return( 64 );
else
return( 32 );
else
if ( value > 4 )
if ( value > 8 )
return( 16 );
else
return( 8 );
else
if ( value > 2 )
return( 4 );
return( value );
}
@markpapadakis
Copy link

From Hacker's Delight: (branchless)

static uint32_t Round_up_to_next_2_power(uint32_t x)
{
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);

   return x + 1;

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment