I have some Fortran code that interprets a binary file. Thanks to another question I asked I understand how the fortran code works but I need help changing it to MATLAB code. Here is the Fortran code:
IMPLICIT NONE
DOUBLE PRECISION SCALE
CHARACTER*72 BLINE
CHARACTER*72 DATA_FILE_FULL_NAME
CHARACTER*6 DATA_FILE_NAME
CHARACTER*4 CH4, CH4F
REAL*4 RL4
EQUIVALENCE (RL4,CH4)
CHARACTER*2 C2
LOGICAL LFLAG
INTEGER*2 I2
if(i2.eq.13881) LFLAG=.FALSE.
c2='69'
LFLAG=.TRUE.
DATA_FILE_FULL_NAME='./'//DATA_FILE_NAME//'.DAT'
OPEN(UNIT=20, FILE=DATA_FILE_FULL_NAME, ACCESS='DIRECT',
. RECL=72, status='OLD')
READ(20,REC=1) BLINE
CH4f=BLINE(7:10)
call flip(4,lflag,ch4f,ch4)
SCALE=RL4
RETURN
END
c ..................................................
subroutine flip(n,lflag,ch1,ch2)
c ..................................................
integer*4 n, i
character*(*) ch1, ch2
logical lflag
if(lflag) then
do i=1,n
ch2(i:i)=ch1(n-i+1:n-i+1)
enddo
else
ch2=ch1
endif
return
end
So basically (and I believe I understand this correctly) the Fortran code is checking the endianess and flipping it if the machine and the data don't match. Additionally, the data is stored in memory in a place reserved for both CH4 and RL4 so by calling RL4 after defining CH4 the data is simply being cast to the REAL*4 type instead of the CHARACTER*4 type. Now I need to figure out how to port this into Matlab. I already have the capability to read in the raw data, but when I try various forms of interpreting it I always get the wrong answer. So far I have tried:
fid=fopen(LMK_file,'r');
BLINE=fread(fid, 72,'char=>char');
CH4=BLINE(7:10);
SCALE=single(CH4(1)+CH4(2)+CH4(3)+CH4(4));
SCALE=int8(CH4(1)+256*int8(CH4(2))+256^2*int8(CH4(3))+256^3*int8(CH4(4));
in MATLAB but both give me the same wrong answer (which makes sense since its doing pretty much the same thing).
Any suggestions?
For anyone else who is looking for the answer to this question this is what I came up with thanks to the help in the comments.
fid=fopen(LMK_file,'r'); %open the file for reading
IGNORE=fread(fid,6,'*char'); %ignore the first 6 bytes. This could also be performed using fseek
SCALE=fread(fid,1,'*float32','b'); %reading in the scale value as a floating point 32 bit number.
where the b
indicates the Big endianess of the file. By using the '*float32' option, fread automatically interprets the next 4 characters as a 32 bit floating point number.
This returns the correct value of scale from the given file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.