How to round a number to the previous power of 2 in C++

2 Answers

0 votes
#include <iostream>
#include <cmath>
 
unsigned int roundToPreviousPowerOf2(unsigned int n) {
    return pow(2, floor(log2(n)));
}
 
int main() {
    unsigned int num = 21;
     
    std::cout << "Previous power of 2: " << roundToPreviousPowerOf2(num) << '\n';
}
 
  
  
/*
run:
  
Previous power of 2: 16
  
*/

 



answered 3 days ago by avibootz
edited 1 day ago by avibootz
0 votes
#include <iostream>
#include <bit> // Requires C++ 20

int roundToPreviousPowerOf2(int n) {
    if (n <= 0) return 0;
    
    // If n is already a power of 2, return n
    if ((n & (n - 1)) == 0) return n;
    
    return 1 << (31 - std::countl_zero(static_cast<unsigned int>(n)));
}

int main() {
    int num = 21;
    
    std::cout << "Previous power of 2: " << roundToPreviousPowerOf2(num) << '\n';
}


/*
run:

Previous power of 2: 16

*/

 



answered 1 day ago by avibootz

Related questions

...