1 package math 2 3 import "math/bits" 4 5 // NextPow2 finds the next power of two (N=2^k, k>=0) greater than n. 6 // If n is already a power of two, then this function returns n, and log2(n). 7 func NextPow2(n uint) (N uint, k uint) { 8 if bits.OnesCount(n) == 1 { 9 k = uint(bits.TrailingZeros(n)) 10 N = n 11 } else { 12 k = uint(bits.Len(n)) 13 N = uint(1) << k 14 } 15 return 16 } 17