簡體   English   中英

如何獲得數字的第一置位的位置

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

例如,我的定義如下所示:

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

我想從最大定義中獲取第一個設置位(從最低有效位開始倒數)的位置。

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

有沒有更好的方法來實現getAmountFromBitwise()?

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

我將其用作您的getAmountFromBitwise()

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

注意,這要求n != 0以獲得正確的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM