Skip to content

Instantly share code, notes, and snippets.

@nojima
Last active August 16, 2024 07:39
Show Gist options
  • Save nojima/0b99df0b0ce66187e0cd5cb22318cfc5 to your computer and use it in GitHub Desktop.
Save nojima/0b99df0b0ce66187e0cd5cb22318cfc5 to your computer and use it in GitHub Desktop.
Efficient way to calculate the minimum power of 2 that is greater than or equal to the given integer
package main
import (
"fmt"
"math/bits"
)
// BitCeil returns the minimum power of 2 that is greater than or equal to x.
// It returns 1 when x is 0.
func BitCeil(x uint) uint {
if x < 2 {
return 1
}
return 1 << (bits.UintSize - bits.LeadingZeros(x-1))
}
func main() {
for i := range 30 {
fmt.Printf("i = %d, BitCeil(i) = %d\n", i, BitCeil(uint(i)))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment