HOG2
SwapEndian.h
Go to the documentation of this file.
1 /*
2  * swapendian.h
3  * games
4  *
5  * Created by Nathan Sturtevant on 3/2/07.
6  * Copyright 2007 Nathan Sturtevant, University of Alberta. All rights reserved.
7  *
8  */
9 
10 #include <stdint.h>
11 
12 #ifndef ENDIAN_H
13 #define ENDIAN_H
14 
15 static inline bool is_little() {
16  int32_t e = 1;
17  return *reinterpret_cast<char*>(&e);
18 }
19 
20 inline uint16_t swap_endian16(uint16_t x)
21 {
22  return (x << 8) | ((x >> 8) & 0xff);
23 }
24 
25 inline uint32_t swap_endian32(uint32_t x)
26 {
27  return (x << 24) | ((x << 8) & 0xff0000) |
28  ((x >> 8) & 0xff00) | ((x >> 24) & 0xff);
29 }
30 
31 inline uint64_t swap_endian64(uint64_t x)
32 {
33  return ((x << 24)&0xFF000000FF000000ll) | ((x << 8) & 0x00FF000000FF0000ll) |
34  ((x >> 8) & 0x0000ff000000ff00ll) | ((x >> 24) & 0x000000FF000000FFll);
35 }
36 
37 inline void little2machine(uint16_t &x)
38 {
39  if (!is_little())
40  x = swap_endian16(x);
41 }
42 
43 inline void little2machine(uint32_t &x)
44 {
45  if (!is_little())
46  x = swap_endian32(x);
47 }
48 
49 inline void little2machine(float &x)
50 {
51  if (!is_little()) {
52 
53  union {
54  uint32_t i;
55  float f;
56  };
57 
58  f = x;
59  swap_endian32(i);
60  x = f;
61  }
62 }
63 
64 inline void little2machine(double &x)
65 {
66  if (!is_little()) {
67 
68  union {
69  uint64_t i;
70  double f;
71  };
72 
73  f = x;
74  swap_endian64(i);
75  x = f;
76  }
77 }
78 
79 #endif
little2machine
void little2machine(uint16_t &x)
Definition: SwapEndian.h:37
is_little
static bool is_little()
Definition: SwapEndian.h:15
swap_endian64
uint64_t swap_endian64(uint64_t x)
Definition: SwapEndian.h:31
swap_endian16
uint16_t swap_endian16(uint16_t x)
Definition: SwapEndian.h:20
swap_endian32
uint32_t swap_endian32(uint32_t x)
Definition: SwapEndian.h:25