Read a text file to binary vector and write it to new file

3 ビュー (過去 30 日間)
Sivan Ben Tzvi
Sivan Ben Tzvi 2019 年 7 月 30 日
回答済み: Deepak 2025 年 6 月 3 日
I want to read a text file to binary vector. The vector i want to convert to the original text and write it to new text file.
I did this: fid = fopen('file1.txt','r'); bin=fread(fid,'*ubit1'); fileID = fopen('test.txt','w'); text=char(bi2de(bin)); fprintf(fileID,'%s \n',text); fclose(fid); fclose(fileID);
Instead of the text i get □□□□□□□□□□□□□□□□□□□□□

回答 (1 件)

Deepak
Deepak 2025 年 6 月 3 日
I understand that you are trying to read a text file as a binary bitstream, reconstruct the original text from it, and write it to a new file. The issue occurs because reading the file with fread(fid, '*ubit1') returns individual bits, not grouped bytes, leading to incorrect character conversion.
We can resolve the issue by grouping the bits into 8-bit chunks (bytes), converting them into ASCII values, and then into characters. Below is the corrected approach:
fid = fopen('file1.txt', 'r');
bin = fread(fid, '*ubit1');
fclose(fid);
bin = bin(1:floor(numel(bin)/8)*8); % Trim to full bytes
bytes = reshape(bin, 8, [])'; % Group into bytes
ascii = bi2de(bytes, 'left-msb'); % Convert to ASCII
text = char(ascii)'; % Convert to characters
fid = fopen('test.txt', 'w');
fprintf(fid, '%s', text);
fclose(fid);
Please find attached the documentation of functions used for reference:
I hope this helps in resolving the issue.

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by