How to round a number to the next power of 2 in C

1 Answer

0 votes
#include <stdio.h>
#include <math.h>

/**
 * Rounds an unsigned integer up to the next power of 2.
 *
 * return The next power of 2 greater than or equal to n
 */
unsigned int roundToNextPowerOf2(unsigned int n) {
    return (unsigned int)pow(2, ceil(log2(n)));
}

int main() {
    unsigned int num = 21;

    printf("Next power of 2: %u\n", roundToNextPowerOf2(num));

    return 0;
}


 
/*
run:
 
Next power of 2: 32
 
*/

 



answered Oct 29, 2025 by avibootz

Related questions

1 answer 72 views
2 answers 76 views
1 answer 179 views
2 answers 227 views
2 answers 81 views
1 answer 95 views
1 answer 88 views
...