Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the fastest algorithm to return the power of a number which is a power of 2?

Tags:

c++

algorithm

Given n = 2^k, how can I find k assuming n is 32-bit integer using C/C++ bitwise?

like image 322
Chan Avatar asked Apr 17 '11 08:04

Chan


People also ask

What number is a power of 2?

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.

How do you find a an element is in power of 2?

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.


2 Answers

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

like image 103
BЈовић Avatar answered Sep 29 '22 18:09

BЈовић


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)

like image 42
Tommy Andersen Avatar answered Sep 29 '22 18:09

Tommy Andersen