1// endianess.h
2//
3// Copyright (c) 2003, Ingo Weinhold (bonefish@cs.tu-berlin.de)
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 2 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, write to the Free Software
17// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18//
19// You can alternatively use *this file* under the terms of the the MIT
20// license included in this package.
21
22#ifndef ENDIANESS_H
23#define ENDIANESS_H
24
25#include <endian.h>
26#include <SupportDefs.h>
27
28/*!
29	\file endianess.h
30	\break Endianess conversion support functions.
31
32	The functions le2h() and h2le() convert various integer types from
33	little endian to host format and vice versa respectively.
34*/
35
36// swap_value
37static inline
38uint8
39swap_value(uint8 v)
40{
41	return v;
42}
43
44// swap_value
45static inline
46int8
47swap_value(int8 v)
48{
49	return v;
50}
51
52// swap_value
53static inline
54uint16
55swap_value(uint16 v)
56{
57	return ((v & 0xff) << 8) | (v >> 8);
58}
59
60// swap_value
61static inline
62int16
63swap_value(int16 v)
64{
65	return (int16)swap_value((uint16)v);
66}
67
68// swap_value
69static inline
70uint32
71swap_value(uint32 v)
72{
73	return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8)
74		   | (v >> 24);
75}
76
77// swap_value
78static inline
79int32
80swap_value(int32 v)
81{
82	return (int32)swap_value((uint32)v);
83}
84
85// swap_value
86static inline
87uint64
88swap_value(uint64 v)
89{
90	return (uint64(swap_value(uint32(v & 0xffffffffULL))) << 32)
91		   | uint64(swap_value(uint32((v & 0xffffffff00000000ULL) >> 32)));
92}
93
94// swap_value
95static inline
96int64
97swap_value(int64 v)
98{
99	return (int64)swap_value((uint64)v);
100}
101
102// le2h
103template<typename T>
104static inline
105T
106le2h(const T &v)
107{
108#if LITTLE_ENDIAN
109	return v;
110#else
111	return swap_value(v);
112#endif
113}
114
115// h2le
116template<typename T>
117static inline
118T
119h2le(const T &v)
120{
121#if LITTLE_ENDIAN
122	return v;
123#else
124	return swap_value(v);
125#endif
126}
127
128#endif	// ENDIANESS_H
129