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].'))
  댓글 수: 1
Andrei Bobrov
Andrei Bobrov 2011년 6월 9일
variant
[8,4,2,1]*reshape(bits,4,[])

댓글을 달려면 로그인하십시오.

카테고리

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