blob: 22ae8b41b8736ddc09cc66e6d2fe76e08e576af8 [file] [log] [blame]
Stefan Reinauera1e48242011-10-21 14:24:57 -07001#ifndef _SWAB_H
2#define _SWAB_H
3
4/*
5 * linux/byteorder/swab.h
6 * Byte-swapping, independently from CPU endianness
7 * swabXX[ps]?(foo)
8 *
9 * Francois-Rene Rideau <fare@tunes.org> 19971205
10 * separated swab functions from cpu_to_XX,
11 * to clean up support for bizarre-endian architectures.
12 *
13 * See asm-i386/byteorder.h and suches for examples of how to provide
14 * architecture-dependent optimized versions
15 *
16 */
17
Sol Boucher158dd552015-05-07 21:00:05 -070018#if !defined(__APPLE__) && !defined(__NetBSD__)
19#define ntohl(x) (is_big_endian() ? (uint32_t)(x) : swab32(x))
20#define htonl(x) (is_big_endian() ? (uint32_t)(x) : swab32(x))
21#elif defined(__NetBSD__)
22#include <arpa/inet.h>
23#endif
24#define ntohll(x) (is_big_endian() ? (uint64_t)(x) : swab64(x))
25#define htonll(x) (is_big_endian() ? (uint64_t)(x) : swab64(x))
26
Stefan Reinauera1e48242011-10-21 14:24:57 -070027/* casts are necessary for constants, because we never know how for sure
28 * how U/UL/ULL map to __u16, __u32, __u64. At least not in a portable way.
29 */
30#define swab16(x) \
31 ((unsigned short)( \
32 (((unsigned short)(x) & (unsigned short)0x00ffU) << 8) | \
33 (((unsigned short)(x) & (unsigned short)0xff00U) >> 8) ))
34
35#define swab32(x) \
36 ((unsigned int)( \
37 (((unsigned int)(x) & (unsigned int)0x000000ffUL) << 24) | \
38 (((unsigned int)(x) & (unsigned int)0x0000ff00UL) << 8) | \
39 (((unsigned int)(x) & (unsigned int)0x00ff0000UL) >> 8) | \
40 (((unsigned int)(x) & (unsigned int)0xff000000UL) >> 24) ))
41
42#define swab64(x) \
43 ((uint64_t)( \
44 (((uint64_t)(x) & (uint64_t)0x00000000000000ffULL) << 56) | \
45 (((uint64_t)(x) & (uint64_t)0x000000000000ff00ULL) << 40) | \
46 (((uint64_t)(x) & (uint64_t)0x0000000000ff0000ULL) << 24) | \
47 (((uint64_t)(x) & (uint64_t)0x00000000ff000000ULL) << 8) | \
48 (((uint64_t)(x) & (uint64_t)0x000000ff00000000ULL) >> 8) | \
49 (((uint64_t)(x) & (uint64_t)0x0000ff0000000000ULL) >> 24) | \
50 (((uint64_t)(x) & (uint64_t)0x00ff000000000000ULL) >> 40) | \
51 (((uint64_t)(x) & (uint64_t)0xff00000000000000ULL) >> 56) ))
52
Sol Boucher158dd552015-05-07 21:00:05 -070053/* common.c */
54int is_big_endian(void);
55
Stefan Reinauera1e48242011-10-21 14:24:57 -070056#endif /* _SWAB_H */