用于计算存储数字n所需的位数的宏

And*_*rei 11 c macros bits c-preprocessor

假设我需要编写C宏来返回存储无符号32位整数所需的位数(1..32).(结果等于上限(log2(n)).

我需要它作为编译时计算宏,而不是函数.

我可以

 #define NBITS(n) ((n)&(1<<31)?32:(n)&(1<<30)?31:...
Run Code Online (Sandbox Code Playgroud)

它有效,但相当长.(速度与此无关,计算在编译时).

有没有更短的方法来编写这个宏?最短的?

Adi*_*Adi 10

#define NBITS2(n) ((n&2)?1:0)
#define NBITS4(n) ((n&(0xC))?(2+NBITS2(n>>2)):(NBITS2(n)))
#define NBITS8(n) ((n&0xF0)?(4+NBITS4(n>>4)):(NBITS4(n)))
#define NBITS16(n) ((n&0xFF00)?(8+NBITS8(n>>8)):(NBITS8(n)))
#define NBITS32(n) ((n&0xFFFF0000)?(16+NBITS16(n>>16)):(NBITS16(n)))
#define NBITS(n) (n==0?0:NBITS32(n)+1)
#include <iostream>
using namespace std;

int main(){
    cout << NBITS(0) << endl;
    cout << NBITS(1) << endl;
    cout << NBITS(2) << endl;
    cout << NBITS(3) << endl;
    cout << NBITS(4) << endl;
    cout << NBITS(1023) << endl;
    cout << NBITS(1024) << endl;
}
Run Code Online (Sandbox Code Playgroud)

这好吗?


Cle*_*lot -3

我不认为 C 预处理器能够做到这一点。如果我没记错的话,您不能将预处理器 if 语句放在宏中。你能做的就是写一段有漏洞的代码,用宏的参数来填补漏洞。