-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendian.h
More file actions
77 lines (64 loc) · 2.36 KB
/
endian.h
File metadata and controls
77 lines (64 loc) · 2.36 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#pragma once
#include <cstdint>
// Big-endian serialization (network byte order)
// Most significant byte first - the standard for wire protocols
namespace endian
{
// Write operations - convert host value to big-endian bytes
inline void write_u8(uint8_t *buf, uint8_t v)
{
buf[0] = v;
}
inline void write_u16(uint8_t *buf, uint16_t v)
{
buf[0] = static_cast<uint8_t>((v >> 8) & 0xFF);
buf[1] = static_cast<uint8_t>(v & 0xFF);
}
inline void write_u32(uint8_t *buf, uint32_t v)
{
buf[0] = static_cast<uint8_t>((v >> 24) & 0xFF);
buf[1] = static_cast<uint8_t>((v >> 16) & 0xFF);
buf[2] = static_cast<uint8_t>((v >> 8) & 0xFF);
buf[3] = static_cast<uint8_t>(v & 0xFF);
}
inline void write_u64(uint8_t *buf, uint64_t v)
{
buf[0] = static_cast<uint8_t>((v >> 56) & 0xFF);
buf[1] = static_cast<uint8_t>((v >> 48) & 0xFF);
buf[2] = static_cast<uint8_t>((v >> 40) & 0xFF);
buf[3] = static_cast<uint8_t>((v >> 32) & 0xFF);
buf[4] = static_cast<uint8_t>((v >> 24) & 0xFF);
buf[5] = static_cast<uint8_t>((v >> 16) & 0xFF);
buf[6] = static_cast<uint8_t>((v >> 8) & 0xFF);
buf[7] = static_cast<uint8_t>(v & 0xFF);
}
// Read operations - convert big-endian bytes to host value
inline uint8_t read_u8(const uint8_t *buf)
{
return buf[0];
}
inline uint16_t read_u16(const uint8_t *buf)
{
return static_cast<uint16_t>(
(static_cast<uint16_t>(buf[0]) << 8) |
static_cast<uint16_t>(buf[1]));
}
inline uint32_t read_u32(const uint8_t *buf)
{
return (static_cast<uint32_t>(buf[0]) << 24) |
(static_cast<uint32_t>(buf[1]) << 16) |
(static_cast<uint32_t>(buf[2]) << 8) |
static_cast<uint32_t>(buf[3]);
}
inline uint64_t read_u64(const uint8_t *buf)
{
return (static_cast<uint64_t>(buf[0]) << 56) |
(static_cast<uint64_t>(buf[1]) << 48) |
(static_cast<uint64_t>(buf[2]) << 40) |
(static_cast<uint64_t>(buf[3]) << 32) |
(static_cast<uint64_t>(buf[4]) << 24) |
(static_cast<uint64_t>(buf[5]) << 16) |
(static_cast<uint64_t>(buf[6]) << 8) |
static_cast<uint64_t>(buf[7]);
}
} // namespace endian