Created
September 28, 2019 13:51
-
-
Save arakis/236280c65ef4ae753a2c3511b4642175 to your computer and use it in GitHub Desktop.
log2 algorithm
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
private static uint[] MultiplyDeBruijnBitPosition = new uint[] | |
{ | |
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, | |
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31, | |
}; | |
/// <summary> | |
/// Find the log base 2 of an N-bit integer in O(lg(N)) operations. | |
/// </summary> | |
/// <remarks> | |
/// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn | |
/// </remarks> | |
public static uint Log2(uint v) | |
{ | |
v |= v >> 1; // first round down to one less than a power of 2 | |
v |= v >> 2; | |
v |= v >> 4; | |
v |= v >> 8; | |
v |= v >> 16; | |
return MultiplyDeBruijnBitPosition[(uint)(v * 0x07C4ACDDU) >> 27]; | |
} | |
private static uint[] MultiplyDeBruijnBitPosition2 = new uint[] | |
{ | |
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, | |
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9, | |
}; | |
/// <summary> | |
/// Find the log base 2 of an N-bit integer in O(lg(N)) operations. Value must be a power of 2. | |
/// </summary> | |
/// <param name="value">Must be a power of 2</param> | |
/// <remarks> | |
/// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn | |
/// </remarks> | |
public static uint Log2OfPowerOf2(uint value) | |
{ | |
return MultiplyDeBruijnBitPosition2[(uint)(value * 0x077CB531U) >> 27]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment