ProsecCoAP 🥂
 
Loading...
Searching...
No Matches
Utils.h
Go to the documentation of this file.
1
5#ifndef __PROSECCOAP_UTILS_H__
6#define __PROSECCOAP_UTILS_H__
7
8#include <Arduino.h>
9#include <stdint.h>
10
17namespace Coap::Utils
18{
24 template <size_t N, typename T>
25 void toNetworkByteOrder(T value, uint8_t (&result)[N])
26 {
27 for (size_t i = 0; i < N; ++i)
28 {
29 // Shift right by (N - 1 - i) * 8 bits, then mask the lowest byte
30 result[i] = static_cast<uint8_t>((value >> ((N - 1 - i) * 8)) & 0xFF);
31 }
32 }
33
37 inline constexpr uint16_t ntohs(uint16_t net_short)
38 {
39#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
40 // If the native platform is already Big-Endian, do nothing
41 return net_short;
42#else
43 // On Little-Endian, swap the 2 bytes
44 return static_cast<uint16_t>((((net_short) & 0xFF00u) >> 8) |
45 (((net_short) & 0x00FFu) << 8));
46#endif
47 }
48
52 inline constexpr uint32_t ntohl(uint32_t net_long)
53 {
54#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
55 // If the native platform is already Big-Endian, do nothing
56 return net_long;
57#else
58 // On Little-Endian, swap the 4 bytes
59 return (((net_long & 0xFF000000ul) >> 24) |
60 ((net_long & 0x00FF0000ul) >> 8) |
61 ((net_long & 0x0000FF00ul) << 8) |
62 ((net_long & 0x000000FFul) << 24));
63#endif
64 }
65
69 inline constexpr uint64_t ntohll(uint64_t net_longlong)
70 {
71#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
72 // If the native platform is already Big-Endian, do nothing
73 return net_longlong;
74#else
75 // On Little-Endian, swap the 8 bytes
76 return (((net_longlong & 0xFF00000000000000ull) >> 56) |
77 ((net_longlong & 0x00FF000000000000ull) >> 40) |
78 ((net_longlong & 0x0000FF0000000000ull) >> 24) |
79 ((net_longlong & 0x000000FF00000000ull) >> 8) |
80 ((net_longlong & 0x00000000FF000000ull) << 8) |
81 ((net_longlong & 0x0000000000FF0000ull) << 24) |
82 ((net_longlong & 0x000000000000FF00ull) << 40) |
83 ((net_longlong & 0x00000000000000FFull) << 56));
84#endif
85 }
86}
87
88#endif
Definition Utils.h:18
void toNetworkByteOrder(T value, uint8_t(&result)[N])
Convert an integer-like value to network byte order (i.e. big-endian).
Definition Utils.h:25
constexpr uint32_t ntohl(uint32_t net_long)
Custom implementation of ntohl (Network to Host Long) for 32-bit integers.
Definition Utils.h:52
constexpr uint16_t ntohs(uint16_t net_short)
Custom implementation of ntohs (Network to Host Short) for 16-bit integers.
Definition Utils.h:37
constexpr uint64_t ntohll(uint64_t net_longlong)
Custom implementation of ntohll (Network to Host Long Long) for 64-bit integers.
Definition Utils.h:69