Last active
October 11, 2016 10:18
-
-
Save patricksuo/e0c747252e5cc74a3b78763c3d21c9c0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package power2 | |
// 如果一个数是2的整数次方,那么 取模 可以有优化成一条 AND 指令 | |
// http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 | |
// 思想是把最高有效位塞给其余的地位,第一次塞1位,第二次塞2位,第三次塞4位 第四次塞8位 第五次塞16位 | |
// 最多需要做 lg(N) 次 SHIFT + lg(N) 次 OR 既可, N是参数的位数 | |
// run on go playground https://play.golang.org/p/-3O7xKuQ-D | |
func RoundUpPowerOf2(a uint32) uint32 { | |
if a <= 1 { | |
return 2 | |
} | |
a-- | |
a = a | (a >> 1) | |
a = a | (a >> 2) | |
a = a | (a >> 4) | |
a = a | (a >> 8) | |
a = a | (a >> 16) | |
a++ | |
return a | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment