1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "bytes.h"
5
6void swap_endian(void *data, unsigned elem_size, unsigned num)
7{
8 char *src = (char *)data;
9 char *dst = src + (elem_size - 1);
10
11 while(num)
12 {
13 unsigned n = elem_size >> 1;
14 char tmp;
15 while(n)
16 {
17 tmp = *src;
18 *src = *dst;
19 *dst = tmp;
20
21 src++;
22 dst--;
23 n--;
24 }
25
26 src = src + (elem_size >> 1);
27 dst = src + (elem_size - 1);
28 num--;
29 }
30}
31
32static_assert(sizeof(unsigned) == 4, "unsigned must be 4 bytes in size");
33static_assert(sizeof(unsigned) == sizeof(int), "unsigned and int must have the same size");
34
35unsigned bytes_be_to_uint(const unsigned char *bytes)
36{
37 return ((bytes[0] & 0xffu) << 24u) | ((bytes[1] & 0xffu) << 16u) | ((bytes[2] & 0xffu) << 8u) | (bytes[3] & 0xffu);
38}
39
40void uint_to_bytes_be(unsigned char *bytes, unsigned value)
41{
42 bytes[0] = (value >> 24u) & 0xffu;
43 bytes[1] = (value >> 16u) & 0xffu;
44 bytes[2] = (value >> 8u) & 0xffu;
45 bytes[3] = value & 0xffu;
46}
47