Fast bit packing?

9 次查看(过去 30 天)
Kevin
Kevin 2011-6-8
Hi everyone,
I am looking for a fast way to do bit packing in Matlab (my data set is pretty big). Here is what I mean by bit packing.
>> bits = [0 0 0 0 1 1 1 0]; % bits = vector of 1's or 0's.
I want each set of 4 bits got packed into a unsigned 4-bit integer, i.e.
>> x = [0 15];
bits(1) = most significant bit of the first integer bits(4) = least significant bit of the first integer
bits(5) = most significant bit of the second integer bits(8) = least significant bit of the second integer
Thanks

回答(2 个)

Jan
Jan 2011-6-8
bits = [0 0 0 0 1 1 1 0];
factor = [8;4;2;1];
x = [bits(1:4) * factor, bits(5:8) * factor]
I assume, this is a very efficient task for a C-mex function, because the Matlab version creates large temporary arrays, if "bits" is large.
  4 个评论
Jan
Jan 2011-6-9
Andrei's "[8,4,2,1]*reshape(bits,4,[])" and Walter's "32bits and TYPECAST" are efficient. But bit-packing seems to be more straight in C, especially for large data.
Walter Roberson
Walter Roberson 2011-6-9
If you are going to be packing in to 32 bits, you would reshape() to group 32 bits at a time, and you would use the appropriate list of powers of 2 depending on the bit order you wanted, with (e.g.)
P2 = 2.^(31:-1:0);
in your initialization and
typecast(uint32(P2*reshape(bits,32,[])),'uint64')
Unless, that is, some of the bits from the second group of 32 bits need to be mixed with the first group. If you do need that kind of mixing, reshape to columns of 64, index the resulting matrix at a permutation matrix, reshape to columns of 32, matrix multiply, uint32, typecast.

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2011-6-8
sum(bsxfun(@times,reshape(bits,4,[]),[8,4,2,1].'))

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by