0

for example, my definition looks like the following:

#define AA              0x0000000000000001LL
#define BB              0x0000000000000002LL
#define CC              0x0000000000000004LL
#define DD              0x0000000000000008LL
#define EE              0x0000000000000010LL
#define FF              0x0000000000000020LL
#define GG              0x0000000000000040LL
#define HH              0x0000000000000080LL

I would like to get the position of the first set bit (counting backwards from the least significant bit) from the maximum definition.

h = getAmountFromBitwise(HH);
output of h is 8;
b = getAmountFromBitwise(BB);
output b is 2;

Is there any better way to implement getAmountFromBitwise()?

int getAmountFromBitwise(long long input) {
  2^x = input;
  y=x+1;
  return y;
}
Hans Lub
  • 5,513
  • 1
  • 23
  • 43
srjohnhuang
  • 232
  • 5
  • 18

1 Answers1

3

I would use this as your getAmountFromBitwise().

int highest_bit_set(long long n) {
  int result = 1;
  while(n >>= 1) /* keep shifting right until n == 0 */
    result++;
  return result;
}

Note that this requires that n != 0 for a correct result.

Hans Lub
  • 5,513
  • 1
  • 23
  • 43