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,900 questions

51,831 answers

573 users

How to round a number to the nearest power of 2 in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/bits"
)

// roundToNearestPowerOf2 returns the power of 2 closest to n.
func roundToNearestPowerOf2(n uint32) uint32 {
    if n == 0 {
        return 0
    }

    // Compute the previous power of 2 using leading zero count
    prev := uint32(1) << (31 - bits.LeadingZeros32(n))
    next := prev << 1

    if n-prev < next-n {
        return prev
    }
    
    return next
}

func main() {
    num := uint32(37)
    
    fmt.Printf("Nearest power of 2: %d\n", roundToNearestPowerOf2(num))
}


/*
run:

Nearest power of 2: 32

*/

 



answered Oct 31, 2025 by avibootz

Related questions

1 answer 50 views
1 answer 50 views
1 answer 83 views
1 answer 112 views
1 answer 145 views
1 answer 58 views
...