Calculating Hamming weight efficiently in matlab

后端 未结 9 1509
你的背包
你的背包 2020-12-09 11:46

Given a MATLAB uint32 to be interpreted as a bit string, what is an efficient and concise way of counting how many nonzero bits are in the string?

I have a working

9条回答
  •  春和景丽
    2020-12-09 12:02

    I'd be interested to see how fast this solution is:

    function r = count_bits(n)
    
    shifts = [-1, -2, -4, -8, -16];
    masks = [1431655765, 858993459, 252645135, 16711935, 65535];
    
    r = n;
    for i=1:5
       r = bitand(bitshift(r, shifts(i)), masks(i)) + ...
          bitand(r, masks(i));
    end
    

    Going back, I see that this is the 'parallel' solution given on the bithacks page.

提交回复
热议问题