4 * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5 * This file is part of DevLib - See devlib/README for information.
8 * \brief Functions to convert integers to/from host byte-order.
12 * \author Bernardo Innocenti <bernie@develer.com>
13 * \author Stefano Fedrigo <aleph@develer.com>
18 *#* Revision 1.7 2005/04/12 04:08:49 bernie
19 *#* host_to_net(16|32)(), net_to_host(16|32)(): New functions.
21 *#* Revision 1.6 2005/04/11 19:10:28 bernie
22 *#* Include top-level headers from cfg/ subdir.
24 *#* Revision 1.5 2004/08/25 14:12:09 rasky
25 *#* Aggiornato il comment block dei log RCS
27 *#* Revision 1.4 2004/07/22 01:08:43 bernie
28 *#* swab32(): Fix a very serious bug.
30 *#* Revision 1.3 2004/07/20 23:47:12 bernie
31 *#* Finally remove redundant protos.
33 *#* Revision 1.2 2004/07/20 17:09:11 bernie
34 *#* swab16(), swab32(), cpu_to_be32(), cpu_to_le32(): New functions.
36 *#* Revision 1.1 2004/07/20 16:26:15 bernie
37 *#* Import byte-order macros into DevLib.
41 #ifndef MWARE_BYTEORDER_H
42 #define MWARE_BYTEORDER_H
44 #include <cfg/compiler.h>
48 * \brief Swap upper and lower bytes in a 16-bit value.
50 INLINE uint16_t swab16(uint16_t x)
52 return ((x & (uint16_t)0x00FFU) << 8)
53 | ((x & (uint16_t)0xFF00U) >> 8);
57 * \brief Reverse bytes in a 32-bit value (e.g.: 0x12345678 -> 0x78563412).
59 INLINE uint32_t swab32(uint32_t x)
61 return ((x & (uint32_t)0x000000FFUL) << 24)
62 | ((x & (uint32_t)0x0000FF00UL) << 8)
63 | ((x & (uint32_t)0x00FF0000UL) >> 8)
64 | ((x & (uint32_t)0xFF000000UL) >> 24);
67 INLINE uint16_t cpu_to_be16(uint16_t x)
69 return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab16(x) : x;
72 INLINE uint16_t cpu_to_le16(uint16_t x)
74 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab16(x) : x;
77 INLINE uint32_t cpu_to_be32(uint32_t x)
79 return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab32(x) : x;
82 INLINE uint32_t cpu_to_le32(uint32_t x)
84 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab32(x) : x;
87 INLINE uint16_t host_to_net16(uint16_t x)
89 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? x : swab16(x);
92 INLINE uint16_t net_to_host16(uint16_t x)
94 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? x : swab16(x);
97 INLINE uint32_t host_to_net32(uint32_t x)
99 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? x : swab32(x);
102 INLINE uint32_t net_to_host32(uint32_t x)
104 return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? x : swab32(x);
107 #endif /* MWARE_BYTEORDER_H */