二进制数求01的变换次数

来源:互联网 发布:男生文具盒淘宝 编辑:程序博客网 时间:2024/04/29 18:14

计算LBP算子的时候遇到计算一个整数求0->1,1->0变换次数的问题。为了能提高性能,前辈告诉一个快速算法,mark下。


int calc_01_change_count(unsigned int n_input){    unsigned int tmp = (n_input << 1);    unsigned int n = n_input^tmp;//check how many bits are different    unsigned int start = (n>>(p)), end = (n & 0x01);//check the first and the last bit    unsigned int count = 0 ;//num of 1->0 or 0->1    for (count = 0; n; ++count)    {        n &= (n - 1) ;    }    count -= (start + end);    return count;}


如果是只计算1的个数可参考:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

原创粉丝点击