Saving data as binary

조회 수: 14 (최근 30일)
Adel Hafri
Adel Hafri 2022년 5월 14일
댓글: Walter Roberson 2022년 5월 20일
Basically, i have for example k = [0 5 4], i want it to be saved as [0 101 100] instead of [00000000 00000101 00000100] so that it takes the least size possible, how can i do that ?

답변 (2개)

Voss
Voss 2022년 5월 14일
k = [0 5 4];
arrayfun(@(x)dec2bin(x,max(1,ceil(log2(x)))),k,'UniformOutput',false)
ans = 1×3 cell array
{'0'} {'101'} {'100'}
  댓글 수: 11
Adel Hafri
Adel Hafri 2022년 5월 15일
can you please go more into detail about how to use fwrite exactly ?
here is more explination what i wanna do exactly:
okay so i have a 750x750 jpeg pictures with values ranging from 0 to 255 and im supposed to apply losless image compression algorithms to reduce the size of those pictures, lossless image compression algorithms such as huffman work by reducing the length of frequent occuring symbols, for example if 150 was my most occuring then my huffman algorithm gives it the code 0 for example and so i ll be saving 7 bits times the frequncy of that data which means compression, the problem is matlab automatically makes that 1 bit length 0 into a 00000000 so essentialy, my algorithm is pointless since matlab will make all the data 8 bit length again, so i want a way to save data exactly the size i want, whether 1 bit,2bits.3....etc instead of it forcing all data to be 8bits
here is an example of how the algorithm changes the symbols
the picture i used isnt the best example of compression but you can get the idea
Walter Roberson
Walter Roberson 2022년 5월 20일
bits = {[1] [0 0] [1] [0 1 1] }
Bitstream = [bits{:}];
fid = fopen('test.bin','w');
fwrite(fid, Bitstream, 'bit1');
fclose(fid);

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


Ilya Dikariev
Ilya Dikariev 2022년 5월 20일
k_new=str2num(dec2bin(k))' would do. But if you want to still reduce the the size, just use dec2bin which keeps the data in char type which is 8 times smaller
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 5월 20일
편집: Walter Roberson 2022년 5월 20일
only 4 times smaller. Each character needs 16 bits.
If you uint8(k_new) then that would need only one byte per value

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

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by