bitcount
Version 1.0.2 (2 KB) by
Matlab Pro
Count the number of set bits in each element. Time and memory efficient
bitcount Counts the number of set bits in each element
Usage:
B = bitcount(A)
Counts the number '1' bits in each element
B = bitcount(A, bitValue)
"bitValue" = 1 = default = counts the occurance of '1'
if bitValue = 0; counts the number '0'
The total bits to verify is [8,16,32,or 64] based on the maximal value of A
B = bitcount(A, bitValue, maxBits)
the total # of bits to examine
The "bitcount" I have implemented here - is much more time/memory efficient vs the Ref above
Efficiency evaluation test: x 10:
maxData = 1e4;
data = uint32(randi([1,intmax('uint32')],1,maxData));
tic;cell2mat(arrayfun(@(x) sum(bitget(x,1:32)),data,'UniformOutput',false)');t_elapsed1 = toc;
tic;bitcount(data);t_elapsed2 = toc;
eff = t_elapsed1 / t_elapsed2;
maxData = 1e4: eff = 10
maxData = 1e5: eff = 20
maxData = 5e5: eff = 40
maxData = 1e6: eff = 56
maxData = 1e7: eff = 128
Examples:
data = 0:15;
out = bitcount(data);
bin_representation = cellfun(@(x) dec2bin(x,4),num2cell(data),'uni',0)';
nBits = num2cell(out)';
disp([num2cell(data(:)), bin_representation, nBits])
% Counts the #'0', default # of bits to examine = 8
data = 0:15;
out = bitcount(data,0); % out = [8 7 7 6 7 6 6 5 7 6 6 5 6 5 5 4]
% Counts the #'0', # of bits to examine = 4
data = 0:15;
out = bitcount(data,0,4); % out = [4 3 3 2 3 2 2 1 3 2 2 1 2 1 1 0]
Created by Noah Safra May 2025
Cite As
Matlab Pro (2025). bitcount (https://www.mathworks.com/matlabcentral/fileexchange/180507-bitcount), MATLAB Central File Exchange. Retrieved .
MATLAB Release Compatibility
Created with
R2024b
Compatible with any release
Platform Compatibility
Windows macOS LinuxTags
Acknowledgements
Inspired by: Bitcount & bitwise hamming distance
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!Discover Live Editor
Create scripts with code, output, and formatted text in a single executable document.