summaryrefslogtreecommitdiffstats
path: root/include/osmocom/core/byteswap.h
blob: 1f09c2b1d53d7c1b3d2dd64b27462ab72430dca3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#pragma once
#include <stdint.h>
#include <osmocom/core/endian.h>

/*! \brief byte-swap a 32bit word
 *  \param[in] in to be swapped 32bit word
 *  \returns byte-swapped 32bit word */
static inline uint32_t osmo_swab32(uint32_t in)
{
	uint32_t out;

	out = (in & 0xff) << 24;
	out |= (in & 0xff00) << 8;
	out |= (in & 0xff0000) >> 8;
	out |= (in & 0xff000000) >> 24;

	return out;
}

/*! \brief byte-swap a 16bit word
 *  \param[in] in to be swapped 16bit word
 *  \returns byte-swapped 16bit word */
static inline uint16_t osmo_swab16(uint16_t in)
{
	uint16_t out;

	out = (in & 0xff) << 8;
	out |= (in & 0xff00) >> 8;

	return out;
}

#ifdef OSMO_IS_LITTLE_ENDIAN
#define osmo_ntohl(x)	osmo_swab32(x)
#define osmo_ntohs(x)	osmo_swab16(x)
#define osmo_htonl(x)	osmo_swab32(x)
#define osmo_htons(x)	osmo_swab16(x)
#else
#define osmo_ntohl(x)	(x)
#define osmo_ntohs(x)	(x)
#define osmo_htonl(x)	(x)
#define osmo_htons(x)	(x)
#endif