Hamming weight for a list of integers in Matlab [duplicate]

一世执手 提交于 2019-12-08 06:16:53

问题


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


来源:https://stackoverflow.com/questions/9396594/hamming-weight-for-a-list-of-integers-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!