MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / LogBase2

Function LogBase2

math/binary/logarithm.go:9–20  ·  view source on GitHub ↗

LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm)

(n uint32)

Source from the content-addressed store, hash-verified

7
8// LogBase2 Finding the exponent of n = 2**x using bitwise operations (logarithm in base 2 of n) [See more](https://en.wikipedia.org/wiki/Logarithm)
9func LogBase2(n uint32) uint32 {
10 base := [5]uint32{0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000}
11 exponents := [5]uint32{1, 2, 4, 8, 16}
12 var result uint32
13 for i := 4; i >= 0; i-- {
14 if n&base[i] != 0 {
15 n >>= exponents[i]
16 result |= exponents[i]
17 }
18 }
19 return result
20}

Callers 2

TestLogBase2Function · 0.85
BenchmarkBitwiseLogBase2Function · 0.85

Calls

no outgoing calls

Tested by 2

TestLogBase2Function · 0.68
BenchmarkBitwiseLogBase2Function · 0.68