Created
May 21, 2014 21:12
-
-
Save rygorous/64a2965486e4458c279f to your computer and use it in GitHub Desktop.
"Simple function to round up to the next power of 2"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//############################################################################ | |
//## ## | |
//## 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 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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);
}