fortran write base64 string of binary to file

Viewed 58

How can I write to a binary file a base64 string representation of data?

program main
   implicit none

   real :: var1, var2, var3, var4
   character(len=:), allocatable :: var

   var1 = 1.23
   var2 = 2.35

   ! var1, var2 written to file, should output "1.23, 2.35"
   var = 'CAAAAKRwnT9mZhZACAAAAAgAAABSuA5AMzOLQAgAAAA='

   open(53, status='scratch', access='stream', action='readwrite', form='unformatted')

   write(53) var1, var2 ! write some data
   write(53) var1+1., var2+2. ! write some more data
   write(53) var ! write the base64 string, I want this line to be the same numbers as the first line I wrote

   rewind(53) ! reset for reading each line we wrote
   read(53) var3, var4 ! read first line
   print *, var3, var4
   read(53) var3, var4 ! read second line
   print *, var3, var4
   read(53) var3, var4 ! read third line, reads as if this was a string representation
   print *, var3, var4
   close(53)
end program main

outputs:

   1.23000002       2.34999990    
   2.23000002       4.34999990    
   12.0784330       4.26526825E+33

I know there is a missing step of converting base64 to a binary form, as the file writes binary data of a string rather than the data it represents, how do I go about converting to binary when writing?

1 Answers

Converting binary data to and from base64 is not such a trivial task. The most reasonable thing you can do is to use one available library.

For Fortran I found only one option,

You can also interface to C libraries, there are several ones, here is for example one in the public domain:

Related