Last active
August 29, 2015 14:01
-
-
Save huwan/b4cecc6c44803a4eaa66 to your computer and use it in GitHub Desktop.
cmath
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
/*! | |
* @brief Checks if n is a power of 2. | |
* @returns true if n is power of 2 | |
*/ | |
static inline bool IsPower2(UINT32 n) | |
{ | |
return ((n & (n - 1)) == 0); | |
} | |
/*! | |
* @brief Computes floor(log2(n)) | |
* Works by finding position of MSB set. | |
* @returns -1 if n == 0. | |
*/ | |
static inline INT32 FloorLog2(UINT32 n) | |
{ | |
INT32 p = 0; | |
if (n == 0) return -1; | |
if (n & 0xffff0000) { p += 16; n >>= 16; } | |
if (n & 0x0000ff00) { p += 8; n >>= 8; } | |
if (n & 0x000000f0) { p += 4; n >>= 4; } | |
if (n & 0x0000000c) { p += 2; n >>= 2; } | |
if (n & 0x00000002) { p += 1; } | |
return p; | |
} | |
/*! | |
* @brief Computes floor(log2(n)) | |
* Works by finding position of MSB set. | |
* @returns -1 if n == 0. | |
*/ | |
static inline INT32 CeilLog2(UINT32 n) | |
{ | |
return FloorLog2(n - 1) + 1; | |
} |
Author
huwan
commented
May 11, 2014
- http://www.stanford.edu/class/cs343/resources/dcache.H
- http://www.cnblogs.com/xueda120/p/3156283.html
- http://www.oschina.net/question/129471_39699
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment