Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

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

2 Answers

0 votes
#include <iostream>
#include <cmath>

unsigned int roundToNearestPowerOf2(unsigned int n) {
    
    if (n <= 0) {
        return 0;
    }
    
    int nextPowerOf2 = pow(2, ceil(log2(n))); // 64 (num = 37)
   
    int prevPowerOf2 = pow(2, floor(log2(n))); // 32 (num = 37)

    // Check which power of 2 is closest to n
    int diff1 = nextPowerOf2 - n; 
    int diff2 = n - prevPowerOf2;
    if (diff1 <= diff2) {
        return nextPowerOf2;
    }
    else {
        return prevPowerOf2;
    }
}

int main() {
    unsigned int num = 37;
    
    std::cout << "Nearest power of 2: " << roundToNearestPowerOf2(num) << std::endl;
}

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

 



answered Oct 29, 2025 by avibootz
0 votes
#include <iostream>
#include <bit> // For std::countl_zero (C++ 20)

unsigned int roundToNearestPowerOf2(unsigned int n) {
    if (n == 0) return 0;

    // Compute the previous power of 2
    unsigned int prevPowerOf2 = 1u << (31 - std::countl_zero(n));

    // Compute the next power of 2
    unsigned int nextPowerOf2 = prevPowerOf2 << 1;

    // Return the one closest to n
    return (n - prevPowerOf2 < nextPowerOf2 - n) ? prevPowerOf2 : nextPowerOf2;
}

int main() {
    unsigned int num = 37;
    
    std::cout << "Nearest power of 2: " << roundToNearestPowerOf2(num) << std::endl;
}

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

 



answered Oct 30, 2025 by avibootz
edited Oct 31, 2025 by avibootz

Related questions

2 answers 52 views
2 answers 40 views
1 answer 95 views
1 answer 42 views
1 answer 57 views
...