I have a .bin file(0's and 1's). I want to read 2 bits of information at a time from that file. How do I do it ?
10 views (last 30 days)
Show older comments
Explanation of the problem :
Suppose I have the binary text as: " 010010001100101011001"
I want to read " 01 " first and then I want to read " 00 " and so on till I read all the data. How do I do it ?
My code:
fileID = fopen("newencryptedmsg.bin");
A = fread(fileID,[1,2],"uint8");
disp(A)
fclose(fileID);
I've written this code but it's giving me the wrong output.
Expeceted Output : 01
Output of my code : 49 48
Can you please help me with this. Thank you.
Answers (2)
Atsushi Ueno
on 9 Aug 2022
Edited: Atsushi Ueno
on 9 Aug 2022
Reproduce the problem:
fileID = fopen('newencryptedmsg.bin','w');
fwrite(fileID,'010010001100101011001');
fclose(fileID);
type newencryptedmsg.bin % It's binary file, but it looks like ASCII file.
fileID = fopen("newencryptedmsg.bin");
A = fread(fileID,[1,2],"uint8");
disp(A)
fclose(fileID);
Correct the problem:
fileID = fopen('newencryptedmsg.bin','w');
fwrite(fileID,[0 1 0 0 1 0 0 0 1 1 0 0 1 0 1 0 1 1 0 0 1]');
fclose(fileID);
type newencryptedmsg.bin
fileID = fopen("newencryptedmsg.bin");
A = fread(fileID,[1,2],"uint8");
disp(A)
fclose(fileID);
fileID = fopen("newencryptedmsg.bin");
A = fread(fileID,"uint8")' % just remove [1,2]
fclose(fileID);
Atsushi Ueno
on 9 Aug 2022
Thank you. Now I understand what you mean. I will revise my answer.
fileID = fopen('newencryptedmsg.bin','w');
fwrite(fileID,'Z'); % the contents is 0x5A (01011010b)
fclose(fileID);
fileID = fopen("newencryptedmsg.bin");
A = fread(fileID,2,'ubit1=>uint8');
disp(A)
fclose(fileID);
0 Comments
See Also
Categories
Find more on Low-Level File I/O in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!