フィルターのクリア

Fast bit packing?

4 ビュー (過去 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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by