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 37 static inline 38 uint8 39 swap_value(uint8 v) 40 { 41 return v; 42 } 43 44 // swap_value 45 static inline 46 int8 47 swap_value(int8 v) 48 { 49 return v; 50 } 51 52 // swap_value 53 static inline 54 uint16 55 swap_value(uint16 v) 56 { 57 return ((v & 0xff) << 8) | (v >> 8); 58 } 59 60 // swap_value 61 static inline 62 int16 63 swap_value(int16 v) 64 { 65 return (int16)swap_value((uint16)v); 66 } 67 68 // swap_value 69 static inline 70 uint32 71 swap_value(uint32 v) 72 { 73 return ((v & 0xff) << 24) | ((v & 0xff00) << 8) | ((v & 0xff0000) >> 8) 74 | (v >> 24); 75 } 76 77 // swap_value 78 static inline 79 int32 80 swap_value(int32 v) 81 { 82 return (int32)swap_value((uint32)v); 83 } 84 85 // swap_value 86 static inline 87 uint64 88 swap_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 95 static inline 96 int64 97 swap_value(int64 v) 98 { 99 return (int64)swap_value((uint64)v); 100 } 101 102 // le2h 103 template<typename T> 104 static inline 105 T 106 le2h(const T &v) 107 { 108 #if LITTLE_ENDIAN 109 return v; 110 #else 111 return swap_value(v); 112 #endif 113 } 114 115 // h2le 116 template<typename T> 117 static inline 118 T 119 h2le(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