Problem reading a binary file in MATLAB

11 views (last 30 days)
Trishia El Chemaly
Trishia El Chemaly on 16 May 2019
Edited: rsneha rani on 22 Nov 2019
I have a binary file that I have converted from .csv to .bin. The .csv file is attached.
I am using the following code to read the .bin file in MATLAB:
fn = 'sample.bin';
fid = fopen(fn, 'r');
dat = fread(fid, '*int16');
fclose(fid);
I have tried both int16 and int32 in the fread function. Still, MATLAB does not read the file correctly.
Original .csv: -1966965
Converted .bin: 00101101 00110001 00111001 00110110 00110110 00111001 00110110 00110101
MATLAB reads the .bin file as:
808529968
825241905
825241632
808464433
808460337
808530225
807416112
808530224
540029233
825307184
808530224
825241632
808464689
808460337
825241905
807415857
808530224
You can check the correct conversion on this website:
What should I change in my code so that MATLAB reads the .bin file correctly?

Answers (2)

Walter Roberson
Walter Roberson on 17 May 2019
A = [808529968
825241905
825241632
808464433
808460337
808530225
807416112
808530224
540029233
825307184
808530224
825241632
808464689
808460337
825241905
807415857
808530224]
char(typecast(uint32(A),'uint8')).'
ans =
'00101101 00110001 00111001 00110110 00110110 00111001 00110110 00110'

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 16 May 2019
Hi,
Here is how you should write your data into a binary file and read it from the binary file.
% Writing in abinary file
A = -1966965;
FID1 = fopen('AA.bin', 'w+');
fwrite(FID1, A, 'float64'); % Precision is float64
fclose(FID1);
%% Reading from binary file:
clearvars
FID2=fopen('AA.bin', 'r');
[AAnew, count]=fread(FID2, [1, 8], 'float64'); % Precision is float64
Good luck.

Community Treasure Hunt

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

Start Hunting!