MATLAB Answers

How to use fread to read little endian data?

I have a .jsf file that I am trying to read which starts off with a 16 byte common message header followed by a 240 byte message 80 specific header and then the data that I am interested in. This data changes for each row of the file. EX) row 7 = 4496 bytes, row 8 = 18704 bytes. If I want to read this data row by row, would I need to use a fseek to position myself 256 bytes into the data to start reading the 4496 bytes or the 18704 bytes and then loop it until the end of the file? The data I am reading will then be fed through image().
FileID = fopen('FileName', 'rb')
while ~feof(FileID)
tline = fgetl(FileID)
Start = fseek( tline, 256, 'cof')
Read = fread(Start)
end

  댓글 수: 0

로그인 to comment.

답변 수: 2

Cris LaPierre 님의 답변 4 Apr 2019
Cris LaPierre 님이 편집함. 4 Apr 2019
 채택된 답변

I would seek first (outside the while loop).
Depending on your data, fgetl may not make sense (files read by bytes don't have end-of-lines). I would think just using fread would do it. You do need to know what the precision is. For example, this will read 4 bytes as a float32.
data1 = fread(fid,1,'float32');
See this post for more details.

  댓글 수: 4

표시 이전 댓글 수: 1
I'd use fseek to skip bytes at the start. The skip in fread is how many bytes to skip AFTER reading. You want to do it before.
Also keep in mind what the actual data is. Images are typically uint8 (1 byte) not float32 (4 bytes). And once you get into the data, I'm not sure you still what to skip after each read.
Is the placement of image(data1) correct? I just wonder if you want an image each time you read, or if you need to first read in all the data and then display the image (so it should go outside the while loop).
Okay then fseek is the way I am going. I have to still look into the percision of the data, the message I have received from the creator of the data said : you skip over the 16 byte header and 240 byte header, and then read the binary data assuming little endian format (8 least significant bits is 1st byte of each 16-bit word, 8 most significant bits is 2nd byte of each 16-bit word). (sorry this is all new to me)
The reason I thought of putting the image(data1) inside the loop is because the data is of a sonar that is moving over time, so it should be like a video of the scanning being done. In the end I am only interested in the objects found on the sonar.
I'd just get the data into MATLAB first. Once it's in, you can loop through the data to display it however you want.
Also, be sure once all the data has been read in to close the file:
fclose(fid);

로그인 to comment.


Jeremy Hughes 님의 답변 4 Apr 2019

The control of byte order is on the creation of the file identifier.https://www.mathworks.com/help/matlab/ref/fopen.html#btrnibn-1-machinefmt
fid = fopen('FileName', 'rb','l')

  댓글 수: 0

로그인 to comment.



Translated by