File: swap_endian.h

package info (click to toggle)
r-cran-readstata13 0.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 804 kB
  • sloc: cpp: 1,770; ansic: 278; makefile: 2
file content (59 lines) | stat: -rw-r--r-- 1,186 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#ifndef SWAP_ENDIAN
#define SWAP_ENDIAN

/*#include <stdint.h>*/
#include <typeinfo>

#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100                \
+ __GNUC_PATCHLEVEL__)

/* Test for GCC < 4.8.0 */
#if GCC_VERSION < 40800 & !__clang__
static inline unsigned short __builtin_bswap16(unsigned short a)
{
  return (a<<8)|(a>>8);
}
#endif

template <typename T>
T swap_endian(T t) {
  if (typeid(T) == typeid(int16_t))
    return __builtin_bswap16(t);
  if (typeid(T) == typeid(uint16_t))
    return __builtin_bswap16(t);

  if (typeid(T)  == typeid(int32_t))
    return __builtin_bswap32(t);
  if (typeid(T)  == typeid(uint32_t))
    return __builtin_bswap32(t);

  if (typeid(T)  == typeid(int64_t))
    return __builtin_bswap64(t);
  if (typeid(T)  == typeid(uint64_t))
    return __builtin_bswap64(t);

  union v {
    double      d;
    float       f;
    uint32_t    i32;
    uint64_t    i64;
  } val;

  if (typeid(T) == typeid(float)){
    val.f = t;
    val.i32 = __builtin_bswap32(val.i32);
    return val.f;
  }

  if (typeid(T) == typeid(double)){
    val.d = t;
    val.i64 = __builtin_bswap64(val.i64);
    return val.d;
  }

  else
    return t;
}

#endif