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

9 views (last 30 days)
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 □□□□□□□□□□□□□□□□□□□□□

Answers (1)

Deepak
Deepak on 3 Jun 2025
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.

Community Treasure Hunt

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

Start Hunting!