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 CenterFile Exchange에서 Text Files에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by