Given n = 2^k, how can I find k assuming n is 32-bit integer using C/C++ bitwise?
1, 2, 4, 8, 16, 32, 64, 128, 256, 512, ... (sequence A000079 in the OEIS) Because two is the base of the binary numeral system, powers of two are common in computer science.
To check if an element is a power of 2: Naive method is to repeatedly divide the element by 2 until it gives either 0 or 1 as the remainder. if the remainder is 1 then its a power of 2 else its not a power of 2. Efficient method: If X & (X – 1) = 0 then X is a power of two.
GCC has __builtin_clz
that translates to BSR on x86/x64, CLZ on ARM, etc. and emulates the instruction if the hardware does not implement it.
Visual C++ 2005 and up has _BitScanReverse
.
Using those functions, you can get your k
Wikipedia writes how to do it using bitwise operators:
/**
* Returns the floor form of binary logarithm for a 32 bit integer.
* −1 is returned if ''n'' is 0.
*/
int floorLog2(unsigned int n) {
if (n == 0)
return -1;
int pos = 0;
if (n >= 1<<16) { n >>= 16; pos += 16; }
if (n >= 1<< 8) { n >>= 8; pos += 8; }
if (n >= 1<< 4) { n >>= 4; pos += 4; }
if (n >= 1<< 2) { n >>= 2; pos += 2; }
if (n >= 1<< 1) { pos += 1; }
return pos;
}
Code taken from: Wikipedia on: Binary Logarithm this page has since been altered the original version with the code sample can still be found her: Wikipedia on: Binary Logarithm (24 May 2011)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With