1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 //
18 
19 #ifndef _LIBS_UTILS_BYTE_ORDER_H
20 #define _LIBS_UTILS_BYTE_ORDER_H
21 
22 #include <stdint.h>
23 #include <sys/types.h>
24 #if defined(_WIN32)
25 #include <winsock2.h>
26 #else
27 #include <netinet/in.h>
28 #endif
29 
30 /*
31  * These macros are like the hton/ntoh byte swapping macros,
32  * except they allow you to swap to and from the "device" byte
33  * order.  The device byte order is the endianness of the target
34  * device -- for the ARM CPUs we use today, this is little endian.
35  *
36  * Note that the byte swapping functions have not been optimized
37  * much; performance is currently not an issue for them since the
38  * intent is to allow us to avoid byte swapping on the device.
39  */
40 
android_swap_long(uint32_t v)41 static inline uint32_t android_swap_long(uint32_t v)
42 {
43     return (v<<24) | ((v<<8)&0x00FF0000) | ((v>>8)&0x0000FF00) | (v>>24);
44 }
45 
android_swap_short(uint16_t v)46 static inline uint16_t android_swap_short(uint16_t v)
47 {
48     return (v<<8) | (v>>8);
49 }
50 
51 #define DEVICE_BYTE_ORDER LITTLE_ENDIAN
52 
53 #if BYTE_ORDER == DEVICE_BYTE_ORDER
54 
55 #define	dtohl(x)	(x)
56 #define	dtohs(x)	(x)
57 #define	htodl(x)	(x)
58 #define	htods(x)	(x)
59 
60 #else
61 
62 #define	dtohl(x)	(android_swap_long(x))
63 #define	dtohs(x)	(android_swap_short(x))
64 #define	htodl(x)	(android_swap_long(x))
65 #define	htods(x)	(android_swap_short(x))
66 
67 #endif
68 
69 #if BYTE_ORDER == LITTLE_ENDIAN
70 #define fromlel(x) (x)
71 #define fromles(x) (x)
72 #define tolel(x) (x)
73 #define toles(x) (x)
74 #else
75 #define fromlel(x) (android_swap_long(x))
76 #define fromles(x) (android_swap_short(x))
77 #define tolel(x) (android_swap_long(x))
78 #define toles(x) (android_swap_short(x))
79 #endif
80 
81 #endif // _LIBS_UTILS_BYTE_ORDER_H
82