libatomprobe
Library for Atom Probe Tomography (APT) computation
endianTest.h
Go to the documentation of this file.
1 /*
2  * endiantTest.h - Platform endian testing
3  * Copyright (C) 2014, D Haley
4 
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14 
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 
19 #ifndef _ENDIAN_TEST_H_
20 #define _ENDIAN_TEST_H_
21 
22 #if defined (_WIN32) || defined(_WIN64) || defined(__CYGWIN__)
23  #ifndef __LITTLE_ENDIAN__
24  #define __LITTLE_ENDIAN__
25  #endif
26 #else
27  #ifdef __linux__
28  #include <endian.h>
29  #endif
30 #endif
31 
32 #ifdef __BYTE_ORDER
33  #if __BYTE_ORDER == __BIG_ENDIAN
34  #ifndef __BIG_ENDIAN__
35  #define __BIG_ENDIAN__
36  #endif
37  #elif __BYTE_ORDER == __LITTLE_ENDIAN
38  #ifndef __LITTLE_ENDIAN__
39  #define __LITTLE_ENDIAN__
40  #endif
41  #elif __BYTE_ORDER == __PDP_ENDIAN
42  #ifndef __ARM_ENDIAN__
43  #define __ARM_ENDIAN__
44  #endif
45  #else
46  #error "Endian determination failed"
47  #endif
48 #endif
49 
50 const int ENDIAN_TEST=1;
51 //Run-time detection
52 inline int is_bigendian() { return (*(char*)&ENDIAN_TEST) == 0 ;}
53 
54 inline int is_littleendian() { return (*(char*)&ENDIAN_TEST) == 1 ;}
55 
56 #include <inttypes.h>
57 
58 inline void floatSwapBytes(float *inFloat)
59 {
60  //Use a union to avoid strict-aliasing error
61  union FloatSwapUnion{
62  float f;
63  char c[4];
64  } ;
65  FloatSwapUnion fa,fb;
66  fa.f = *inFloat;
67 
68  fb.c[0] = fa.c[3];
69  fb.c[1] = fa.c[2];
70  fb.c[2] = fa.c[1];
71  fb.c[3] = fa.c[0];
72 
73  *inFloat=fb.f;
74 }
75 
76 inline void int4SwapBytes(int32_t *inInt)
77 {
78  //Use a union to avoid strict-aliasing error
79  union IntSwapUnion{
80  int i;
81  char c[4];
82  } ;
83  IntSwapUnion ia,ib;
84  ia.i = *inInt;
85 
86  ib.c[0] = ia.c[3];
87  ib.c[1] = ia.c[2];
88  ib.c[2] = ia.c[1];
89  ib.c[3] = ia.c[0];
90 
91  *inInt=ib.i;
92 }
93 
94 #endif
const int ENDIAN_TEST
Definition: endianTest.h:50
int is_bigendian()
Definition: endianTest.h:52
void int4SwapBytes(int32_t *inInt)
Definition: endianTest.h:76
int is_littleendian()
Definition: endianTest.h:54
void floatSwapBytes(float *inFloat)
Definition: endianTest.h:58