KADATH
fread_be.cpp
1 /*
2  Copyright 2017 Philippe Grandclement
3 
4  This file is part of Kadath.
5 
6  Kadath is free software: you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 3 of the License, or
9  (at your option) any later version.
10 
11  Kadath is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with Kadath. If not, see <http://www.gnu.org/licenses/>.
18 */
19 
20 // C headers
21 #include <stdio.h>
22 #include <assert.h>
23 namespace Kadath {
24  //-------------------------//
25  // int version //
26  //-------------------------//
27 
28 int fread_be(int* aa, int size, int nb, FILE* fich) {
29 
30  assert(size == 4) ;
31 
32  // Determines whether the default storage is big endian
33  // or large endians
34 
35  int itest = 1 ;
36  bool little_endian = ( *( reinterpret_cast<char*>(&itest) ) == 1) ;
37 
38  if (little_endian) {
39 
40  int size_tot = 4 * nb ;
41 
42  char* bytes_big = new char[size_tot] ;
43 
44  int nr = static_cast<int>(fread(bytes_big, 1, size_tot, fich)) ;
45 
46  char* pbig = bytes_big ;
47  char* plit = reinterpret_cast<char*>( aa ) ;
48 
49  for (int j=0; j< nb; j++) {
50 
51  for (int i=0; i<4; i++) {
52  plit[i] = pbig[3-i] ;
53  }
54 
55  plit += 4 ; // next item
56  pbig += 4 ;
57 
58  }
59 
60  delete [] bytes_big ;
61 
62  return nr / 4 ;
63 
64  }
65  else { // Big endian case: nothing to do:
66 
67  return static_cast<int>(fread(aa, size, nb, fich)) ;
68  }
69 
70 }
71 
72  //-------------------------//
73  // double version //
74  //-------------------------//
75 
76 int fread_be(double* aa, int size, int nb, FILE* fich) {
77 
78  assert(size == 8) ;
79 
80  // Determines whether the default storage is big endian
81  // or large endians
82 
83  int itest = 1 ;
84  bool little_endian = ( *( reinterpret_cast<char*>(&itest) ) == 1) ;
85 
86  if (little_endian) {
87 
88  int size_tot = 8 * nb ;
89 
90  char* bytes_big = new char[size_tot] ;
91 
92  int nr = static_cast<int>(fread(bytes_big, 1, size_tot, fich)) ;
93 
94  char* pbig = bytes_big ;
95  char* plit = reinterpret_cast<char*>( aa ) ;
96 
97  for (int j=0; j< nb; j++) {
98 
99  for (int i=0; i<8; i++) {
100  plit[i] = pbig[7-i] ;
101  }
102 
103  plit += 8 ; // next item
104  pbig += 8 ;
105 
106  }
107 
108  delete [] bytes_big ;
109 
110  return nr / 8 ;
111 
112  }
113  else { // Big endian case: nothing to do:
114 
115  return static_cast<int>(fread(aa, size, nb, fich)) ;
116  }
117 
118 }
119 }