存储一个数n所需的比特宏数计算 [英] Macro to compute number of bits needed to store a number n

查看:264
本文介绍了存储一个数n所需的比特宏数计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我需要写的 C 宏返回(1..32)来存储32位无符号整数所需的比特数。 (结果等于上限(LOG2(N))。

我需要它作为编译时计算的宏,不是一个函数。

我可以做

 的#define NBITS(N)((N)及(1 LT;< 31)32:(N)及(1 LT;小于30)31 :.? ..

它的工作原理,但比较长。 (速度无所谓这里,计算是在编译时)。

有短写这个宏的方法吗?最短?


解决方案

 的#define NBITS2(N)((N和2)?​​1:0)
的#define NBITS4(n)的((N放大器;(位于0xC))(2 + NBITS2(N GT;&→2)):( NBITS2(正)))
的#define NBITS8(n)的((N放大器; 0XF0)(4 + NBITS4(N GT;&→4)):( NBITS4(正)))
的#define NBITS16(n)的((N放大器;为0xFF00)(8 + NBITS8(N GT;→8)):( NBITS8(正)))
的#define NBITS32(n)的((N放大器; 0xFFFF0000地址)(16 + NBITS16(N GT;> 16)):( NBITS16(正)))
#定义NBITS(N)(N == 0?0:NBITS32(N)+1)
#包括LT&;&iostream的GT;
使用命名空间std;诠释主(){
    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;
}

这是件好事?

Let's say I need to write C macro that returns number of bits(1..32) needed to store unsigned 32-bit integer. (Result equals ceiling(log2(n)).

I need it as compile-time computed macro, not a function.

I could do

 #define NBITS(n) ((n)&(1<<31)?32:(n)&(1<<30)?31:...

it works, but is rather long. (Speed does not matter here, computation is at compile time).

Is there shorter way to write this macro ? Shortest ?

解决方案

#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;
}

it is good?

这篇关于存储一个数n所需的比特宏数计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆