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

采纳的回答

Cedric
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
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)
Cedric
Cedric 2013-3-2
编辑:Cedric 2013-3-2
I completely understand, James. As I wrote above, I've been trying to push people around me quite a bit on related topics, for years, and without any success!

请先登录,再进行评论。

更多回答(1 个)

James Tursa
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).

类别

Help CenterFile Exchange 中查找有关 Performance and Memory 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by