Fortranバイナリデータを書いて、CとPython(numpy)で読む

Ubuntu-14.04 64bit上のgcc-4.8.4でテスト。

test.F90

program test
  implicit none

  integer :: i, j, count
  real(kind=8) :: data(4, 3)

  print '("Number of bits used for data:", i5)', storage_size(data)
  
  count = 1
  do i = 1, 4
     do j = 1, 3
        data(i, j) = count
        write(*, '(F15.8)', advance='no') data(i, j)
        count = count + 1
     end do
     print *, ''
  end do
  open(unit=11, file="data.bin", status="REPLACE", access="STREAM")
  write(11) data
  close(unit=11)

end program test
% gfortran test.F90
% ./a.out
Number of bits used for data:   64
     1.00000000     2.00000000     3.00000000
     4.00000000     5.00000000     6.00000000
     7.00000000     8.00000000     9.00000000
    10.00000000    11.00000000    12.00000000

test.c

#include<stdio.h>

int main(void) {
  FILE *fp;
  int i, j;
  double x;
  
  printf("Number of bits used for data: %d\n", (int)(sizeof(double) * 8));

  fp = fopen("data.bin", "rb");
  if (!fp) {
    printf("File open failed.\n");
    return 1;
  }

  for (j = 0; j < 3; j++) {
    for (i = 0; i < 4; i++) {
      fread(&x, sizeof(double), 1, fp);
      printf("%f ", x);
    }
    printf("\n");
  }

  return 0;
}
% gcc test.c
% ./a.out
Number of bits used for data: 64
1.000000 4.000000 7.000000 10.000000
2.000000 5.000000 8.000000 11.000000
3.000000 6.000000 9.000000 12.000000

test.py

#!/usr/bin/python

import numpy as np

shape = (3, 4)
dt = np.dtype(('double', shape))
print("Number data type is %s." % dt)
data = np.fromfile("data.bin", dtype=dt)[0]
print(data)
% ./test.py
Number data type is ('<f8', (3, 4)).
[[  1.   4.   7.  10.]
 [  2.   5.   8.  11.]
 [  3.   6.   9.  12.]]