PROGRAM TEST
IMPLICIT NONE
CHARACTER(1)::B
INTEGER::MAT(100),I
! To Read 8 bit Binary Files
OPEN(UNIT=1,FILE='file_read.bin',FORM='UNFORMATTED',ACCESS='STREAM')
DO I=1,100
READ(1) B
MAT(I)=ICHAR(B)
ENDDO
CLOSE(1)
! To Write 8 bit Binary Files
OPEN
(UNIT=1,FILE='file_write.bin',FORM='UNFORMATTED',ACCESS='STREAM')
DO I=1,50
WRITE(1) CHAR(MAT(I))
ENDDO
CLOSE
(1)
STOP
END PROGRAM TEST
However i can read and write integer values between 0-255 (8 bit or
2^8). I there a way to read / write 16 or 32 bit integer values?
See the documentation for the selected_in_kind() intrinsic procedure
for your compiler. Note, that the range for integer types normally
goes from [-huge(i)-1:huge(i)] for some integer variable i.
troutmask:kargl[89] cat l.f90
program a
integer, parameter :: ik = selected_int_kind(2), jk =
selected_int_kind(4)
integer(ik) i
integer(jk) j
print '(3(I0,1X))', range(i), huge(i), digits(i)
print '(3(I0,1X))', range(j), huge(j), digits(j)
end program a
troutmask:kargl[90] gfc -o z l.f90
troutmask:kargl[91] ./z
2 127 7
4 32767 15
--
steve
Fortran does not have unsigned numbers. Using characters is an ugly
hack for unsigned 8-bit.
> I there a way to read / write 16 or 32 bit integer values?
You need an INTEGER data type. You could try INTEGER*2 (16 bits) or
INTEGER*4 (32 bits), but that is not standard Fortran. Also you will
get flamed for suggesting it. [smile]
The standard way is to find the "right" kind. selected_int_kind(N)
returns the kind number of an integer which holds N decimal digits
(signed). It is NOT necessarily the number of bytes used. Then you
declare an integer to be of that kind.
See any good reference on Fortran for a fuller discussion of this
topic.
--- elliot
You just need to avoid the strange translation integer/character and
read/write integer values directly :
PROGRAM TEST
IMPLICIT NONE
INTEGER::mat(100)
mat=1
OPEN(UNIT=1,FILE='file_write.bin',FORM='UNFORMATTED',ACCESS='STREAM')
WRITE(10) mat ! all the values in a single write statement
CLOSE(10)
mat=0
OPEN(UNIT=20,FILE='file_write.bin',FORM='UNFORMATTED',ACCESS='STREAM')
READ(20) mat
WRITE(*,*) mat
END PROGRAM TEST
Additional remark : avoid file units less than 7. They often
correspond to predefined units.
I guess that it depends on whether you want to process arbitrary
binary files, or whether you just want to read and write
32-bit integers (and other things such as REALs, etc.
So, which is it?
Thank you everyone,
francois.jacq's suggestion worked really well. I was making mistake of
converting it to characters and back to integers. If i do not do that
then it takes any values larger that 2^8.
Thank you once again.