在C编程中计算带符号的32位整数的二进制位数 [英] Counting the binary digits of a signed 32-bit integer in c programming

查看:304
本文介绍了在C编程中计算带符号的32位整数的二进制位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数,用于计算无符号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:我想您知道吗-除非您的处理器对此有特殊说明,并且您有对其进行访问-最快的计数位数之一是:

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屋!

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