最快的方法来计算在一个unsigned int位转换的数 [英] Fastest way to count number of bit transitions in an unsigned int

查看:267
本文介绍了最快的方法来计算在一个unsigned int位转换的数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在 unsigned int类型计数位跃迁数的最快方式。

如果整型包括: 0b00000000000000000000000000001010

跃迁的数目是:4

如果整型包括: 0b00000000000000000000000000001001

跃迁的数目是:3

语言是C。


解决方案

  INT numTransitions(int类型的)
{
  INT B = A>> 1; // SIGN延伸转变正确计算在两端位
  INT C = A ^ B; //异或标记是不一样的左边的邻居位
  返回CountBits(C); //在C组位计数
}

对于一个有效的执行 CountBits的看到的 http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel

I'm looking for the fastest way of counting the number of bit transitions in an unsigned int.

If the int contains: 0b00000000000000000000000000001010

The number of transitions are: 4

If the int contains: 0b00000000000000000000000000001001

The number of transitions are: 3

Language is C.

解决方案

int numTransitions(int a)
{
  int b = a >> 1; // sign-extending shift properly counts bits at the ends
  int c = a ^ b;  // xor marks bits that are not the same as their neighbors on the left
  return CountBits(c); // count number of set bits in c
}

For an efficient implementation of CountBits see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel

这篇关于最快的方法来计算在一个unsigned int位转换的数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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