in Matlab, I'm trying to pack arbitrary bit-length unsigned integers (e.g., an array of 3-bit integers) into an array of uint8. Given the tip here, I can generate code that works for "small" arrays (say 10,000 elements), but it consumes all memory for large arrays (such as 16 million elements). The code I use is below, borrowing from previous postings:
function x_bytes = stuff_bits(x, n)
r = dec2bin(x,n); % bitstring for each uint in x
s = reshape(r',[],1); % one continuous string of bits
t = reshape(str2num(s),8,[])'; % array of 8-bit numbers (stuffed)
u = t*(2.^(size(t,2)-1:-1:0))'; % array of bytes representing all the bits stuffed together
x_bytes = uint8(u); % should be compressed byte stream
end
I realize that I'm taking a uint, converting it to a string, then converting it back to a bit; I've also read that dec2bin is not terribly efficient.
When I try this with 16mil elements (on a 64-bit windows box with 8 GB of memory), all memory is consumed. Blah. So I loop over subsections and it requires about 10 minutes to complete the 16mil elements. So, something is very inefficient.
Anyone got a better way to generate bit strings like python's BitArray?
thanks,
xdecimal numbers, and you want to convert each one to a binary number that is a constant length (3-bits) and then you want to compact all the 3-bit numbers into a sequence of bits and then separate it into uint8s? sox=[6 2 5 4] -> [110,010,101,100] -> [110010101100] ->[00001100,10101100] -> [12,172]? Or am I not understanding the question?tinto 8 very large numbers, not a bunch of 8bit numbers. Tryu=(2.^(7:-1:0))*t;