Include top-level headers from cfg/ subdir.
[bertos.git] / mware / byteorder.h
1 /*!
2  * \file
3  * <!--
4  * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
5  * This file is part of DevLib - See devlib/README for information.
6  * -->
7  *
8  * \brief Functions to convert integers to/from host byte-order.
9  *
10  * \version $Id$
11  *
12  * \author Bernardo Innocenti <bernie@develer.com>
13  * \author Stefano Fedrigo <aleph@develer.com>
14  */
15
16 /*#*
17  *#* $Log$
18  *#* Revision 1.6  2005/04/11 19:10:28  bernie
19  *#* Include top-level headers from cfg/ subdir.
20  *#*
21  *#* Revision 1.5  2004/08/25 14:12:09  rasky
22  *#* Aggiornato il comment block dei log RCS
23  *#*
24  *#* Revision 1.4  2004/07/22 01:08:43  bernie
25  *#* swab32(): Fix a very serious bug.
26  *#*
27  *#* Revision 1.3  2004/07/20 23:47:12  bernie
28  *#* Finally remove redundant protos.
29  *#*
30  *#* Revision 1.2  2004/07/20 17:09:11  bernie
31  *#* swab16(), swab32(), cpu_to_be32(), cpu_to_le32(): New functions.
32  *#*
33  *#* Revision 1.1  2004/07/20 16:26:15  bernie
34  *#* Import byte-order macros into DevLib.
35  *#*
36  *#*/
37
38 #ifndef MWARE_BYTEORDER_H
39 #define MWARE_BYTEORDER_H
40
41 #include <cfg/compiler.h>
42 #include <cfg/cpu.h>
43
44 /*!
45  * \brief Swap upper and lower bytes in a 16-bit value.
46  */
47 INLINE uint16_t swab16(uint16_t x)
48 {
49         return    ((x & (uint16_t)0x00FFU) << 8)
50                 | ((x & (uint16_t)0xFF00U) >> 8);
51 }
52
53 /*!
54  * \brief Reverse bytes in a 32-bit value (e.g.: 0x12345678 -> 0x78563412).
55  */
56 INLINE uint32_t swab32(uint32_t x)
57 {
58         return    ((x & (uint32_t)0x000000FFUL) << 24)
59                 | ((x & (uint32_t)0x0000FF00UL) <<  8)
60                 | ((x & (uint32_t)0x00FF0000UL) >>  8)
61                 | ((x & (uint32_t)0xFF000000UL) >> 24);
62 }
63
64 INLINE uint16_t cpu_to_be16(uint16_t x)
65 {
66         return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab16(x) : x;
67 }
68
69 INLINE uint16_t cpu_to_le16(uint16_t x)
70 {
71         return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab16(x) : x;
72 }
73
74 INLINE uint32_t cpu_to_be32(uint32_t x)
75 {
76         return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab32(x) : x;
77 }
78
79 INLINE uint32_t cpu_to_le32(uint32_t x)
80 {
81         return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab32(x) : x;
82 }
83
84 #endif /* MWARE_BYTEORDER_H */