1 /*
2  * Copyright 2023, Cypress Semiconductor Corporation (an Infineon company)
3  * SPDX-License-Identifier: Apache-2.0
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 /*
18  * Byte order utilities
19  *
20  * This file by default provides proper behavior on little-endian architectures.
21  * On big-endian architectures, IL_BIGENDIAN should be defined.
22  */
23 
24 #ifndef INCLUDED_WHD_ENDIAN_H
25 #define INCLUDED_WHD_ENDIAN_H
26 
27 #ifdef __cplusplus
28 extern "C"
29 {
30 #endif
31 
32 /* Reverse the bytes in a 16-bit value */
33 #define SWAP16(val) \
34     ( (uint16_t)( ( ( (uint16_t)(val) & (uint16_t)0x00ffU ) << 8 ) | \
35                   ( ( (uint16_t)(val) & (uint16_t)0xff00U ) >> 8 ) ) )
36 
37 /* Reverse the bytes in a 32-bit value */
38 #define SWAP32(val) \
39     ( (uint32_t)( ( ( (uint32_t)(val) & (uint32_t)0x000000ffU ) << 24 ) | \
40                   ( ( (uint32_t)(val) & (uint32_t)0x0000ff00U ) <<  8 ) | \
41                   ( ( (uint32_t)(val) & (uint32_t)0x00ff0000U ) >>  8 ) | \
42                   ( ( (uint32_t)(val) & (uint32_t)0xff000000U ) >> 24 ) ) )
43 
44 #ifdef IL_BIGENDIAN
45 #define htod32(i) SWAP32(i)
46 #define htod16(i) SWAP16(i)
47 #define dtoh32(i) SWAP32(i)
48 #define dtoh16(i) SWAP16(i)
49 #define hton16(i) (i)
50 #define hton32(i) (i)
51 #define ntoh16(i) (i)
52 #define ntoh32(i) (i)
53 #else /* IL_BIGENDIAN */
54 #define htod32(i) (i)
55 #define htod16(i) (i)
56 #define dtoh32(i) (i)
57 #define dtoh16(i) (i)
58 #define hton16(i) SWAP16(i)
59 #define hton32(i) SWAP32(i)
60 #define ntoh16(i) SWAP16(i)
61 #define ntoh32(i) SWAP32(i)
62 #endif /* IL_BIGENDIAN */
63 
64 #ifdef __cplusplus
65 } /* extern "C" */
66 #endif
67 
68 #endif /* INCLUDED_WHD_ENDIAN_H */
69 
70