blob: cecdc63efac00d864d6592cb0cb417db31039ba5 [file] [log] [blame]
Neels Hofmeyr17518fe2017-06-20 04:35:06 +02001/*! \file byteswap.h */
2
Harald Welte3318c652017-05-15 12:07:51 +02003#pragma once
4#include <stdint.h>
5#include <osmocom/core/endian.h>
6
Neels Hofmeyr87e45502017-06-20 00:17:59 +02007/*! byte-swap a 32bit word
Harald Welte3318c652017-05-15 12:07:51 +02008 * \param[in] in to be swapped 32bit word
9 * \returns byte-swapped 32bit word */
10static 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 Hofmeyr87e45502017-06-20 00:17:59 +020022/*! byte-swap a 16bit word
Harald Welte3318c652017-05-15 12:07:51 +020023 * \param[in] in to be swapped 16bit word
24 * \returns byte-swapped 16bit word */
25static 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 Alteholzcefce662018-04-07 23:06:29 +020035#if OSMO_IS_LITTLE_ENDIAN == 1
Harald Welte3318c652017-05-15 12:07:51 +020036#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