在c编程中计算有符号32位整数的二进制数字 [英] Counting the binary digits of a signed 32-bit integer in c programming
问题描述
我有以下函数来计算一个无符号 32 位整数中的二进制位数.
I have following function which counts the number of binary digits in an unsigned 32-bit integer.
uint32_t L(uint32_t in)
{
uint32_t rc = 0;
while (in)
{
rc++;
in >>= 1;
}
return(rc);
}
如果是有符号的 32 位整数,谁能告诉我,我应该采取哪种方法?实现二进制补码是一种选择.如果您有更好的方法,请告诉我.
Could anyone tell me please in case of signed 32-bit integer, which approach i should take ? implementing two's complement is an option. if you have any better approach, please let me know.
推荐答案
关于:
uint32_t count_bits(int32_t in)
{
uint32_t unsigned_in = (uint32_t) in;
uint32_t rc = 0;
while (unsigned_in)
{
rc++;
unsigned_in >>= 1;
}
return(rc);
}
只需将 signed int 转换为 unsigned 并执行与以前相同的操作.
Just convert the signed int into an unsigned one and do the same thing as before.
顺便说一句:我想你知道 - 除非你的处理器有一个特殊的指令并且你可以访问它 - 计算位的最快实现之一是:
BTW: I guess you know that - unless your processor has a special instruction for it and you have access to it - one of the fastest implementation of counting the bits is:
int count_bits(unsigned x) {
x = x - ((x >> 1) & 0xffffffff);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x + (x >> 4)) & 0x0f0f0f0f;
x = x + (x >> 8);
x = x + (x >> 16);
return x & 0x0000003f;
}
虽然它不是最快的...
It's not the fastest though...
这篇关于在c编程中计算有符号32位整数的二进制数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!