Created
February 28, 2017 16:43
-
-
Save gobwas/161be8e2b58fbad9d544ce776f4151a2 to your computer and use it in GitHub Desktop.
This file contains 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
func log2(n uint) uint { | |
const uintBits = 32 << (^uint(0) >> 63) | |
var ( | |
seen, bit uint | |
m, l, r uint | |
) | |
r = uintBits | |
for l < r { | |
m = l + (r-l)/2 | |
bit = 1 << m | |
if seen&bit != 0 { | |
if n^bit != 0 { | |
m++ | |
} | |
break | |
} | |
seen |= bit | |
switch n >> m { | |
case 0: | |
r = m // decrease | |
default: | |
l = m // increase | |
} | |
} | |
return m | |
} | |
func ceilPowerOfTwo(n int) int { | |
n-- | |
n |= n >> 1 | |
n |= n >> 2 | |
n |= n >> 4 | |
n |= n >> 8 | |
n |= n >> 16 | |
n++ | |
return n | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment