Neels Hofmeyr | 17518fe | 2017-06-20 04:35:06 +0200 | [diff] [blame] | 1 | /*! \file byteswap.h */ |
| 2 | |
Harald Welte | 3318c65 | 2017-05-15 12:07:51 +0200 | [diff] [blame] | 3 | #pragma once |
| 4 | #include <stdint.h> |
| 5 | #include <osmocom/core/endian.h> |
| 6 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 7 | /*! byte-swap a 32bit word |
Harald Welte | 3318c65 | 2017-05-15 12:07:51 +0200 | [diff] [blame] | 8 | * \param[in] in to be swapped 32bit word |
| 9 | * \returns byte-swapped 32bit word */ |
| 10 | static inline uint32_t osmo_swab32(uint32_t in) |
| 11 | { |
| 12 | uint32_t out; |
| 13 | |
| 14 | out = (in & 0xff) << 24; |
| 15 | out |= (in & 0xff00) << 8; |
| 16 | out |= (in & 0xff0000) >> 8; |
| 17 | out |= (in & 0xff000000) >> 24; |
| 18 | |
| 19 | return out; |
| 20 | } |
| 21 | |
Neels Hofmeyr | 87e4550 | 2017-06-20 00:17:59 +0200 | [diff] [blame] | 22 | /*! byte-swap a 16bit word |
Harald Welte | 3318c65 | 2017-05-15 12:07:51 +0200 | [diff] [blame] | 23 | * \param[in] in to be swapped 16bit word |
| 24 | * \returns byte-swapped 16bit word */ |
| 25 | static inline uint16_t osmo_swab16(uint16_t in) |
| 26 | { |
| 27 | uint16_t out; |
| 28 | |
| 29 | out = (in & 0xff) << 8; |
| 30 | out |= (in & 0xff00) >> 8; |
| 31 | |
| 32 | return out; |
| 33 | } |
| 34 | |
Thorsten Alteholz | cefce66 | 2018-04-07 23:06:29 +0200 | [diff] [blame] | 35 | #if OSMO_IS_LITTLE_ENDIAN == 1 |
Harald Welte | 3318c65 | 2017-05-15 12:07:51 +0200 | [diff] [blame] | 36 | #define osmo_ntohl(x) osmo_swab32(x) |
| 37 | #define osmo_ntohs(x) osmo_swab16(x) |
| 38 | #define osmo_htonl(x) osmo_swab32(x) |
| 39 | #define osmo_htons(x) osmo_swab16(x) |
| 40 | #else |
| 41 | #define osmo_ntohl(x) (x) |
| 42 | #define osmo_ntohs(x) (x) |
| 43 | #define osmo_htonl(x) (x) |
| 44 | #define osmo_htons(x) (x) |
| 45 | #endif |