我正在尝试使用 x*x-1 检查整数是否为 2 的幂,然后对其进行计数。
long count_bits(long n) {
unsigned int c;
for c = 0:n
n = n * (n - 1);  %Determines if an integer is a power of two!
c=c+1;
end
disp(c);
在这里找到了我的答案:在matlab中有效地计算汉明权重
我正在尝试使用 x*x-1 检查整数是否为 2 的幂,然后对其进行计数。
long count_bits(long n) {
unsigned int c;
for c = 0:n
n = n * (n - 1);  %Determines if an integer is a power of two!
c=c+1;
end
disp(c);
在这里找到了我的答案:在matlab中有效地计算汉明权重
使用bitget:
% generate a random int number
>> n = uint32( randi( intmax('uint32'), 1, 1 ) )
n = 
   3771981510
>> count = sum(bitget(n,1:32))
count = 
   18
或者,如果您关心性能,您可以使用查找表 (LUT) 来计算位数:
为 8 位整数构建 LUT(仅 256 个条目):
function lut = countBitsLUT()
for ii = 0:255
    lut(ii+1) = sum(bitget(uint8(ii),1:8));
end
您只需构建 LUT 一次。
获得 LUT 后,您可以使用以下方法计算位数:
count = lut( bitand(n,255)+1 ) + ...      % how many set bits in first byte
        lut( bitand( bitshift(n,-8), 255 ) + 1 ) + ... % how many set bits in second byte
        lut( bitand( bitshift(n,-16), 255 ) + 1 ) + ... % how many set bits in third byte
        lut( bitand( bitshift(n,-24), 255 ) + 1 ); % how many set bits in fourth byte
我还做了一个小“基准”:
lutCount = @( n ) lut( bitand(n,255)+1 ) + ...      % how many set bits in first byte
        lut( bitand( bitshift(n,-8), 255 ) + 1 ) + ... % how many set bits in second byte
        lut( bitand( bitshift(n,-16), 255 ) + 1 ) + ... % how many set bits in third byte
        lut( bitand( bitshift(n,-24), 255 ) + 1 ); % how many set bits in fourth byte
t = [ 0 0 ];
for ii=1:1000
    n = uint32( randi( intmax('uint32'), 1, 1 ) );
    tic;
    c1 = sum(bitget(n,1:32));
    t(1) = t(1) + toc;
    tic;
    c2 = lutCount( n );
    t(2) = t(2) + toc;
    assert( c1 == c2 );
end
运行时间是:
t = [0.0115    0.0053]
sum也就是说,LUT 的速度是的两倍bitget。