File: byte_order.h

package info (click to toggle)
megaglest 3.13.0-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 12,844 kB
  • ctags: 18,191
  • sloc: cpp: 144,280; ansic: 11,861; sh: 3,233; perl: 1,904; python: 1,751; objc: 142; asm: 42; makefile: 24
file content (79 lines) | stat: -rw-r--r-- 1,821 bytes parent folder | download | duplicates (6)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// ==============================================================
//	This file is part of MegaGlest (www.megaglest.org)
//
//	Copyright (C) 2012 Mark Vejvoda
//
//	You can redistribute this code and/or modify it under
//	the terms of the GNU General Public License as published
//	by the Free Software Foundation; either version 2 of the
//	License, or (at your option) any later version
// ==============================================================

#ifndef BYTE_ORDER_H
#define BYTE_ORDER_H

#include <algorithm>
#include "leak_dumper.h"

namespace Shared{ namespace PlatformByteOrder {

template<class T> T EndianReverse(T t) {
//	unsigned char uc[sizeof t];
//	memcpy(uc, &t, sizeof t);
//
//	for (unsigned char *b = uc, *e = uc + sizeof(T) - 1; b < e; ++b, --e) {
//		std::swap(*b, *e);
//	}
//	memcpy(&t, uc, sizeof t);
//	return t;

	char& raw = reinterpret_cast<char&>(t);
    std::reverse(&raw, &raw + sizeof(T));
    return t;
}

inline static bool isBigEndian() {
	short n = 0x1;
	return (*(char*)(&n) == 0x0);
}


template<class T> T toCommonEndian(T t) {
	static bool bigEndianSystem = isBigEndian();
	if(bigEndianSystem == true) {
		t = EndianReverse(t);
	}
	return t;
}

template<class T> T fromCommonEndian(T t) {
	static bool bigEndianSystem = isBigEndian();
	if(bigEndianSystem == true) {
		t = EndianReverse(t);
	}
	return t;
}

template<class T>
void toEndianTypeArray(T *data, size_t size) {
	static bool bigEndianSystem = isBigEndian();
	if(bigEndianSystem == true) {
		for(size_t i = 0; i < size; ++i) {
			data[i] = toCommonEndian(data[i]);
		}
	}
}

template<class T>
void fromEndianTypeArray(T *data, size_t size) {
	static bool bigEndianSystem = isBigEndian();
	if(bigEndianSystem == true) {
		for(size_t i = 0; i < size; ++i) {
			data[i] = fromCommonEndian(data[i]);
		}
	}
}

}}

#endif