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

1 Answer

0 votes
package main

import (
    "fmt"
    "math"
)

// roundToPreviousPowerOf2 returns the previous power of 2 less than or equal to n.
func roundToPreviousPowerOf2(n int) int {
    if n <= 0 {
        return 0
    }
    return int(math.Pow(2, math.Floor(math.Log2(float64(n)))))
}

func main() {
    num := 21
    
    fmt.Printf("Previous power of 2: %d\n", roundToPreviousPowerOf2(num))
}




/*
run:
 
Previous power of 2: 16
 
*/

 



answered Oct 30, 2025 by avibootz

Related questions

1 answer 61 views
1 answer 72 views
1 answer 108 views
1 answer 173 views
1 answer 74 views
1 answer 71 views
...