Matlab 计算整数中的设定位数?
我试着用x*x-1来检查整数是否是2的幂,然后数一数Matlab 计算整数中的设定位数?,matlab,binary,lookup-tables,Matlab,Binary,Lookup Tables,我试着用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); 在这里找到我的答案:使用bitget: % generate a random int number >> n = uint32( randi( intma
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);
在这里找到我的答案:使用
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位整数(仅256个条目)构造LUT:
您只需要构造一次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
我还做了一个小的“基准测试”:
运行时间为:
t = [0.0115 0.0053]
也就是说,LUT的速度大约是
bitget
的sum
的两倍。问题可能是如何混合C和matlab代码并使其工作……您的问题到底是什么?你想知道一个特定的数字是否是二的幂吗?你想把Matlab和C代码混合在一起吗?你是@aka.nice还是@Supa?@slayton我不是上文,也许我应该用引号“我怎么能…”。我的评论只是对提议的代码的一个观察。。。理解的反讽可能是一个很好的工具,但一旦被解释,它就会分崩离析。
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]