Read data from binary file

80 views (last 30 days)
Morten Seiger
Morten Seiger on 5 May 2020
Edited: Morten Seiger on 5 May 2020
Hi all.
I am having trouble with reading a dataset in binary format. I have tried with the 'fread' and 'fopen' function, but can't seem to get what I want.
The binary file should be a dataset for some wind velocity. When using the 'fread' and 'fopen' I just get a lot of integers, that doesn't look like the typical development in wind velocity fluctuations:
%%%
data1 = fread(fopen('data.bin','r'));
plot(data1(1:1000))
%%%
I also tried to separate the data into more columns, which also don't look like the solution to my problem:
%%%
noc = 8; %Number of columns
data = reshape(data1,noc,length(data1)/noc)';
for i = 1:noc
subplot(noc,1,i),plot((0:1:length(data)-1),data(:,i)),xlim([0,1000])
end
%%%
Do I need to convert this to something else, or can anyone give me a hint in the right direction? It might be my lack of knowledge for binary files.
Best regards

Accepted Answer

Mehmed Saad
Mehmed Saad on 5 May 2020
Edited: Mehmed Saad on 5 May 2020
By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer (uint8), and returns a double array.
So you need to convert it to binary array.
To convert a number to binary array de2bi is used in matlab
For example
de2bi(1,8)
ans =
1 0 0 0 0 0 0 0
it reutrns an 8 bit binary array (as i specified it in 2nd argument) and msb is on right.
Now if i have two numbers
de2bi([1 2],8)
ans =
1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
Also if you want to read double from binary file you can directly use
fread(fileID,'double')
For example
I write a double value 0.101 in binary file doubledata.bin
fileID = fopen('doubledata.bin','w');
fwrite(fileID,0.101,'double');
fclose(fileID)
Now i am reading it
fileID = fopen('doubledata.bin');
fread(fileID,'double')
ans =
0.1010

More Answers (0)

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!