gitee.com/gricks/utils@v1.0.8/power.go (about) 1 package utils 2 3 const ( 4 bitsize = 32 << (^uint(0) >> 63) 5 maxint = int(1<<(bitsize-1) - 1) 6 maxintHeadBit = 1 << (bitsize - 2) 7 ) 8 9 // LogRange logarithmic range iterates from ceiled to power of two min to max 10 func LogRange(min, max int) []int { 11 if min <= 0 { 12 panic("unexpected min range") 13 } 14 r := []int{} 15 for i := Ceilp2(min); i <= max; i <<= 1 { 16 r = append(r, i) 17 } 18 return r 19 } 20 21 // Isp2 reports whether given integer is a power of two. 22 func Isp2(n int) bool { 23 return n&(n-1) == 0 24 } 25 26 // Ceilp2 returns the least power of two integer value greater than 27 // or equal to n. 28 func Ceilp2(n int) int { 29 if n&maxintHeadBit != 0 && n > maxintHeadBit { 30 panic("argument is too large") 31 } 32 if n <= 2 { 33 return n 34 } 35 n-- 36 n = fillBits(n) 37 n++ 38 return n 39 } 40 41 // Floorp2 returns the greatest power of two integer value less than 42 // or equal to n. 43 func Floorp2(n int) int { 44 if n <= 2 { 45 return n 46 } 47 n = fillBits(n) 48 n >>= 1 49 n++ 50 return n 51 } 52 53 func fillBits(n int) int { 54 n |= n >> 1 55 n |= n >> 2 56 n |= n >> 4 57 n |= n >> 8 58 n |= n >> 16 59 n |= n >> 32 60 return n 61 }