I have tested that program on a x86_64 machine:
program writing_bytes
use ISO_FORTRAN_ENV, only: INT8, INT16
implicit none
integer(INT8) :: i8, j8
integer(INT16) :: i16
character(len=1) :: c1
integer :: status
! 129 = 0x81 = 0b10000001
i8 = int(z'81', kind=INT8)
print *, i8
i16 = 129
j8 = int(i16, kind=INT8)
print *, j8
c1 = achar(129)
open(unit=1, file='bytes.bin', access='stream', status='replace', &
& action='write', iostat=status)
write(1, iostat=status) i8, j8, c1
close(1, iostat=status)
call execute_command_line("hexdump -C bytes.bin")
end program
This is the output:
$ gfortran writing_bytes.f90 && ./a.out
-127
-127
00000000 81 81 81 |...|
00000003
It does the job on my machine, both with int( , kind=int8)
and achar()
. Will it work on any processor?
Note also that if you write i8 = int(129, kind=INT8)
, gfortran complains:
Error: Arithmetic overflow converting INTEGER(4) to INTEGER(1) at (1). This check can be disabled with the option ‘-fno-range-check’: