openscenegraph
Endian
Go to the documentation of this file.
1/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
2 *
3 * This library is open source and may be redistributed and/or modified under
4 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
5 * (at your option) any later version. The full license is in LICENSE file
6 * included with this distribution, and on the openscenegraph.org website.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * OpenSceneGraph Public License for more details.
12*/
13
14#ifndef OSG_ENDIAN
15#define OSG_ENDIAN 1
16
17#include <algorithm>
18
19namespace osg {
20
21enum Endian
22{
23 BigEndian,
24 LittleEndian
25};
26
27inline Endian getCpuByteOrder()
28{
29 union {
30 char big_endian_1[2];
31 short is_it_really_1;
32 } u;
33 u.big_endian_1[0] = 0;
34 u.big_endian_1[1] = 1;
35
36 if (u.is_it_really_1 == 1)
37 return BigEndian;
38 else
39 return LittleEndian;
40}
41
42inline void swapBytes( char* in, unsigned int size )
43{
44 char* start = in;
45 char* end = start+size-1;
46 while (start<end)
47 {
48 std::swap(*start++,*end--);
49 }
50}
51
52inline void swapBytes2( char* in )
53{
54 std::swap(in[0],in[1]);
55}
56
57inline void swapBytes4( char* in )
58{
59 std::swap(in[0],in[3]);
60 std::swap(in[1],in[2]);
61}
62
63inline void swapBytes8( char* in )
64{
65 std::swap(in[0],in[7]);
66 std::swap(in[1],in[6]);
67 std::swap(in[2],in[5]);
68 std::swap(in[3],in[4]);
69}
70
71inline void swapBytes16( char* in )
72{
73 std::swap(in[0],in[15]);
74 std::swap(in[1],in[14]);
75 std::swap(in[2],in[13]);
76 std::swap(in[3],in[12]);
77 std::swap(in[4],in[11]);
78 std::swap(in[5],in[10]);
79 std::swap(in[6],in[9]);
80 std::swap(in[7],in[8]);
81}
82
83template<typename T>
84void swapBytes(T& t) { swapBytes(reinterpret_cast<char*>(&t), sizeof(T)); }
85
86}
87
88#endif