Check Parity of a uint32 Without Converting to a Binary String?
3 次查看(过去 30 天)
显示 更早的评论
In the simplest form, my task is to count the number of ones in a 32 bit unsigned integer. To do this, I am currently converting the integers to binary strings with “dec2bin”. The problem is I need to count the ones in millions of 32 bit data words, and the binary strings take up too much space, so I’m forced to do small chunks at a time. Is there a way to do this without converting from the uint32 class?
Thanks
0 个评论
采纳的回答
Cedric
2013-3-1
编辑:Cedric
2013-3-1
But if I had 30s to find a solution for doing it "by hand" in MATLAB, I would build something like that:
>> a = uint32(31) ; sum(bitand(a, uint32(2.^(0:31)))~=0)
ans =
5
Cheers,
Cedric
EDIT: or, to operate on an array of uint32's:
>> data = uint32(1:16) ;
>> masks = uint32(2.^(0:31)) ;
>> counts = arrayfun(@(d)sum(bitand(d, masks)~=0), data)
counts =
1 1 2 1 2 2 3 1 2 2 3 2 3 3 4 1
EDIT2: or even faster:
>> data = uint32(1:1e6) ; % Example with 1 million uint32's.
>> counts = sum( bitand(repmat(data(:), 1, 32), ...
repmat(uint32(2.^(0:31)), numel(data), 1)) ~= 0, ...
2 ) ;
8 个评论
James Tursa
2013-3-2
编辑:James Tursa
2013-3-2
For 64-bit installations I guess I can empathize ... but for 32-bit installations MATLAB comes with the lcc compiler already pre-installed. Given the types of memory and speed advantages that can be gained with mex routines, particularly when one is working with very large arrays, IMO it is worth it to invest a little time in learning how to use the mex stuff. Heck, just how hard is it to type this at the command line:
mex onbits.c
(Comments not directed at you personally Cedric ... just a side rant on my part)
更多回答(1 个)
James Tursa
2013-3-1
编辑:James Tursa
2013-3-1
See this FEX submission:
Should be pretty fast for your application, but I will warn you that it does not use the fastest C algorithm. I know of faster algorithms but haven't updated this submission yet. I also haven't updated it yet to be self-building, so you will have to manually build the C mex routine (see the instructions).
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Performance and Memory 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!