Reading binary files with fread

4 次查看(过去 30 天)
jnaumann
jnaumann 2013-12-10
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.

回答(1 个)

Image Analyst
Image Analyst 2013-12-10
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

类别

Help CenterFile Exchange 中查找有关 Images 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by