Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

Format question

Intel_C_Intel
Employee
1,204 Views
I am reading and writing to a binary file.
If a read a number into a character variable how do I read it back as a number?
In the example below iver is a 2-byte integer and is '4'. It is written to the file then read into a 2-byte character cver. I want to then read it back into a 2-byte integer to get 4 again.
I think I use a format statement such as B2 Z2 ??
I have ony ever used A,I,F,X for reading and writing text files - how can I read the binary value?

Thanks,

David

integer*2 iver
character cver*2

open (55,file='c:	est.gbf',access='direct',form='binary',recl=1)
iver=4
write (55,rec=87) iver
read (55,rec=87) cver
read (cver,'(Z2)') iver
close (55)
0 Kudos
6 Replies
james1
Beginner
1,204 Views
I'm not sure why you don't just read it back in the way you wrote it out, but the easy answer with the case you provided is just equivalence your character variable to the integer variable.

James
0 Kudos
Intel_C_Intel
Employee
1,204 Views
The actual case is more complex than the example.
The 2-byte character variable cver is sent as a parameter to a routine and from it I want to get the number '4'.

I tried iver=cver but it doesn't compile -
'The assignment operation or the binary expression operation is invalid for the data types of the two operands'

all that I can think of is -
open (47,STATUS='scratch',ACCESS='direct',FORM='binary',RECL=1)
write (47,rec=1) cver
read (47,rec=1) iver
close (47,STATUS='DELETE')


Which is a long-winded way do do iver=cver

David
0 Kudos
james1
Beginner
1,204 Views
Right, this is why I said to use EQUIVALENCE, in which case you do not need to make an assignment between incompatible variables. Something like

character*2 cver
character*2 tver
integer*2 iver
equivalence (tver, iver)
tver = cver

Now iver has the integer representation of cver.

James
0 Kudos
Jugoslav_Dujic
Valued Contributor II
1,204 Views
See also TRANSFER intrinsics (basically, it does bit-by-bit copy from incompatible variables).
0 Kudos
Intel_C_Intel
Employee
1,204 Views
Thanks, that works, I didn't know about equivalence.
David
0 Kudos
billaustralia
Beginner
1,204 Views
you need to be aware that equivalencing char and integer is non standard in fortran 77, 90 and 95.

Your original problem seems to be you have a 2 byte char, and you need to read the integer in it. Use an internal read.

integer i
character c*2
c=' 4'
read(c,'(i2)')i
0 Kudos
Reply