The fread function read data in binary format, thus sequences of 0s and 1s. Therefore, you can read raw data just as a sequence of 0s and 1s, or you can divide it into words (bytes) and give these words a numerical meaning which is not binary, but for example decimal. Let me give you an example:
Let us first save into a binary file called example.bin the numbers 7 and 15 as unsigned integers of 8bits
fileID = fopen('example.bin','w');
fwrite(fileID,[7,15],'uint8','ieee-be');
fclose(fileID);
If we read this file using the same format of 8bit unsigned integer, the fread will return the same data as we saved:
fileID = fopen('example.bin');
A = fread(fileID,2,'uint8','ieee-be')'
fclose(fileID);
A =
7 15
However, the same data can be read in other formats! We now set fread input parameters to read this data in a raw format, i.e., just as a sequence of 0s and 1s. Therefore, one bit at a time. Since data were saved in 8bit words, let us read two times a bunch of 8 bits:
fileID = fopen('example.bin');
B1 = fread(fileID,8,'ubit1','ieee-be')'
B2 = fread(fileID,8,'ubit1','ieee-be')'
fclose(fileID);
B1 =
0 0 0 0 0 1 1 1
B2 =
0 0 0 0 1 1 1 1
The first 8 bits encode the number 7 in binary notation, the others 15. This is the way fwrite stores the data. So, when using fread function, it is important to be aware of the TYPE of data we are reading (e.g., uint8, uint16, etc), the size this data occupy for each encoded character and the number of characters we want to read.
Check out the fread help page.
2 Comments
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/322819-binary-file-reader-using-fread-function#comment_425056
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/322819-binary-file-reader-using-fread-function#comment_425056
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/322819-binary-file-reader-using-fread-function#comment_425095
Direct link to this comment
https://se.mathworks.com/matlabcentral/answers/322819-binary-file-reader-using-fread-function#comment_425095
Sign in to comment.