swab16(), swab32(), cpu_to_be32(), cpu_to_le32(): New functions.
[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.2  2004/07/20 17:09:11  bernie
19  * swab16(), swab32(), cpu_to_be32(), cpu_to_le32(): New functions.
20  *
21  * Revision 1.1  2004/07/20 16:26:15  bernie
22  * Import byte-order macros into DevLib.
23  *
24  */
25
26 #ifndef MWARE_BYTEORDER_H
27 #define MWARE_BYTEORDER_H
28
29 #include <compiler.h>
30 #include <cpu.h>
31
32 /*!
33  * \brief Swap upper and lower bytes in a 16-bit value.
34  */
35 INLINE uint16_t swab16(uint16_t x);
36 INLINE uint16_t swab16(uint16_t x)
37 {
38         return    ((x & (uint16_t)0x00FFU) << 8)
39                 | ((x & (uint16_t)0xFF00U) >> 8);
40 }
41
42 /*!
43  * \brief Reverse bytes in a 32-bit value (e.g.: 0x12345678 -> 0x78563412).
44  */
45 INLINE uint16_t swab32(uint16_t x);
46 INLINE uint16_t swab32(uint16_t x)
47 {
48         return    ((x & (uint32_t)0x000000FFUL) << 24)
49                 | ((x & (uint32_t)0x0000FF00UL) <<  8)
50                 | ((x & (uint32_t)0x00FF0000UL) >>  8)
51                 | ((x & (uint32_t)0xFF000000UL) >> 24);
52 }
53
54 INLINE uint16_t cpu_to_be16(uint16_t x);
55 INLINE uint16_t cpu_to_be16(uint16_t x)
56 {
57         return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab16(x) : x;
58 }
59
60 INLINE uint16_t cpu_to_le16(uint16_t x);
61 INLINE uint16_t cpu_to_le16(uint16_t x)
62 {
63         return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab16(x) : x;
64 }
65
66 INLINE uint32_t cpu_to_be32(uint32_t x);
67 INLINE uint32_t cpu_to_be32(uint32_t x)
68 {
69         return (CPU_BYTE_ORDER == CPU_LITTLE_ENDIAN) ? swab32(x) : x;
70 }
71
72 INLINE uint32_t cpu_to_le32(uint32_t x);
73 INLINE uint32_t cpu_to_le32(uint32_t x)
74 {
75         return (CPU_BYTE_ORDER == CPU_BIG_ENDIAN) ? swab32(x) : x;
76 }
77
78 #endif /* MWARE_BYTEORDER_H */