KADATH
fwrite_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 
21 // C headers
22 #include <cstdio>
23 #include <cstdint>
24 #include <cassert>
25 #include <type_traits>
26 
27 namespace Kadath {
28  //-------------------------//
29  // int version //
30  //-------------------------//
31 
32 int fwrite_be(const int* aa, int size, int nb, FILE* fich) {
33 
34  assert(size == 4) ;
35 
36  // Determines whether the default storage is big endian
37  // or large endians
38 
39  int itest = 1 ;
40  bool little_endian = ( *( reinterpret_cast<char*>(&itest) ) == 1) ;
41 
42  if (little_endian) {
43 
44  int size_tot = 4 * nb ;
45 
46  char* bytes_big = new char[size_tot] ;
47  char* pbig = bytes_big ;
48  const char* plit = reinterpret_cast<const char*>(aa) ;
49 
50  for (int j=0; j< nb; j++) {
51 
52  for (int i=0; i<4; i++) {
53  pbig[i] = plit[3-i] ;
54  }
55 
56  plit += 4 ; // next item
57  pbig += 4 ;
58 
59  }
60 
61 
62  int nx = static_cast<int>(fwrite(bytes_big, 1, size_tot, fich)) / 4 ;
63 
64  delete [] bytes_big ;
65 
66  return nx ;
67 
68  }
69  else { // Big endian case: nothing to do:
70 
71  return static_cast<int>(fwrite(aa, size, nb, fich)) ;
72  }
73 
74 }
75 
76 
77  //-------------------------//
78  // double version //
79  //-------------------------//
80 
81 
82 int fwrite_be(const double* aa, int size, int nb, FILE* fich) {
83 
84  assert(size == 8) ;
85 
86  // Determines whether the default storage is big endian
87  // or large endians
88 
89  int itest = 1 ;
90  bool little_endian = ( *( reinterpret_cast<char*>(&itest) ) == 1) ;
91 
92  if (little_endian) {
93 
94  int size_tot = 8 * nb ;
95 
96  char* bytes_big = new char[size_tot] ;
97  char* pbig = bytes_big ;
98  const char* plit = reinterpret_cast<const char*>(aa) ;
99 
100  for (int j=0; j< nb; j++) {
101 
102  for (int i=0; i<8; i++) {
103  pbig[i] = plit[7-i] ;
104  }
105 
106  plit += 8 ; // next item
107  pbig += 8 ;
108 
109  }
110 
111  int nx = static_cast<int>(fwrite(bytes_big, 1, size_tot, fich)) / 8 ;
112  delete [] bytes_big ;
113 
114  return nx ;
115 
116  }
117  else { // Big endian case: nothing to do:
118 
119  return static_cast<int>(fwrite(aa, size, nb, fich)) ;
120  }
121 
122 }}