Reading binary files with fread
2 views (last 30 days)
Show older comments
Hi everyone,
I am trying to read a signal from a binary file. After lots of head scratching I have found a way of doing this. This is my current code.
fid=fopen(filename);
A=fread(fid,'bit8');
New1a=reshape(New1,2,numel(New1)/2);
New1a(1,:)=New1a(1,:)*0.000305176;
ispositive=New1a(1,:)>=0;
New1a(1,ispositive)=(New1a(1,ispositive))+(New1a(2,ispositive)*0.078125056);
New1a(1,~ispositive)=(New1a(1,~ispositive))+((New1a(2,~ispositive)+1)*0.078125056);
Although this works, the method seems a bit convoluted. Have I missed a trick somewhere and is there a easier (and possibly quicker) way of doing the same thing? Here the 0.000305176 is the resolution and the signal range is +/-10V.
0 Comments
Answers (1)
Image Analyst
on 10 Dec 2013
You don't need to do all that. Just read it in as a 2D array initially. Here, see this snippet from my code:
% Read in image2D image data
% Get original, full-sized 2-D slice.
% Note: fread() requires that x_size and y_size be doubles.
% Note: fread() will return a 2D array if you pass in a 2D array for the number of bytes, as in [x_size y_size].
if stHeader.BytesPerVoxel == 1
oneSlice = fread(fileHandle, [x_size y_size], '*uint8');
elseif stHeader.BytesPerVoxel == 2
oneSlice = fread(fileHandle, [x_size y_size], '*int16'); % It will be a 2D array after this.
else
error('Unsupported BytesPerVoxel %d', stHeader.BytesPerVoxel);
end
0 Comments
See Also
Categories
Find more on Whos 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!