简体   繁体   English

如何获得数字的第一置位的位置

[英]How to get the position of the first set bit of a number

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()? 有没有更好的方法来实现getAmountFromBitwise()?

int getAmountFromBitwise(long long input) {
  2^x = input;
  y=x+1;
  return y;
}

I would use this as your getAmountFromBitwise() . 我将其用作您的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. 注意,这要求n != 0以获得正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM