计算不同位的个数

ORBSLAM2中计算描述子距离时用到了计算不同位的个数
没看懂很神奇记下来

// Bit set count operation from
// http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
    int32_t a[8];
    int32_t b[8];
    memset(a,0xFFFFFFF,8*sizeof(int32_t));
    memset(b,0,8*sizeof(int32_t));
    int32_t* pa = a;
    int32_t* pb = b;
    int dist=0;
    for(int i=0; i<8; i++, pa++, pb++)
    {
        cout << *pa << " " << *pb << endl;
        unsigned  int v = *pa ^ *pb;
        v = v - ((v >> 1) & 0x55555555);
        v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
        dist += (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
    }
    cout << dist << endl;
//输出256

posted @ 2019-01-22 17:34  narjaja  阅读(171)  评论(0编辑  收藏  举报