Hamming weight for a list of integers in Matlab [d

2019-06-01 17:15发布

问题:

This question already has an answer here:

  • Calculating Hamming weight efficiently in matlab 9 answers

Quite a simple problem: I have a list of integers, e.g.,

 a = [7 8]

Now I want to have a seperate list, that contains the Hamming Weight (that is the number of 1 bits in the binary represenation) for each of the integers in the list. That means the result for the integer list above should look as follows:

 res = [3 1]

Anyone an idea how I could do this quickly?

回答1:

This is a little hacky, but it works:

res = sum( dec2bin(a).' == '1' );

It converts a to binary representation, looks at how many characters in that representation are '1', and sums up those numbers.



回答2:

#% Quickly for a few or quickly for millions?
#% A quick method for a 32 bit int requires a 16 bit look-up table
#% Ideally the table is created once and passed to the function for usage
#% vectorized
vt=randi(2^32,[4096*4096,1])-1; #% input vector vt

num_ones=uint8(zeros(65536,1));
for i=0:65535
 num_ones(i+1)=length( find( bitget( i, 1:32 ) ) ) ;
end % 0.43 sec to create table

v=num_ones(mod(vt,65536)+1)+num_ones(floor(vt/65536)+1); #% 0.85 sec
% dec2bin is 1000 times slower