stdex
Additional custom or not Standard C++ covered algorithms
Loading...
Searching...
No Matches
endian.hpp
1/*
2 SPDX-License-Identifier: MIT
3 Copyright © 2023 Amebis
4*/
5
6#pragma once
7
8#include "sal.hpp"
9#include "system.hpp"
10#include <assert.h>
11#include <stdint.h>
12
13#ifdef _WIN32
14#if REG_DWORD == REG_DWORD_LITTLE_ENDIAN
15#elif REG_DWORD == REG_DWORD_BIG_ENDIAN
16#define BIG_ENDIAN
17#else
18#error Unknown endian
19#endif
20#else
21#include <endian.h>
22#if __BYTE_ORDER == __LITTLE_ENDIAN
23#elif __BYTE_ORDER == __BIG_ENDIAN
24#define BIG_ENDIAN
25#else
26#error Unknown endian
27#endif
28#endif
29
30namespace stdex
31{
32 inline uint16_t byteswap(_In_ const uint16_t value)
33 {
34 #if _MSC_VER >= 1300
35 return _byteswap_ushort(value);
36 #elif defined(_MSC_VER)
37 uint16_t t = (value & 0x00ff) << 8;
38 t |= (value) >> 8;
39 return t;
40 #else
41 return __builtin_bswap16(value);
42 #endif
43 }
44
45 inline uint32_t byteswap(_In_ const uint32_t value)
46 {
47 #if _MSC_VER >= 1300
48 return _byteswap_ulong(value);
49 #elif defined(_MSC_VER)
50 uint32_t t = (value & 0x000000ff) << 24;
51 t |= (value & 0x0000ff00) << 8;
52 t |= (value & 0x00ff0000) >> 8;
53 t |= (value) >> 24;
54 return t;
55 #else
56 return __builtin_bswap32(value);
57 #endif
58 }
59
60 inline uint64_t byteswap(_In_ const uint64_t value)
61 {
62 #if _MSC_VER >= 1300
63 return _byteswap_uint64(value);
64 #elif defined(_MSC_VER)
65 uint64_t t = (value & 0x00000000000000ff) << 56;
66 t |= (value & 0x000000000000ff00) << 40;
67 t |= (value & 0x0000000000ff0000) << 24;
68 t |= (value & 0x00000000ff000000) << 8;
69 t |= (value & 0x000000ff00000000) >> 8;
70 t |= (value & 0x0000ff0000000000) >> 24;
71 t |= (value & 0x00ff000000000000) >> 40;
72 t |= (value) >> 56;
73 return t;
74 #else
75 return __builtin_bswap64(value);
76 #endif
77 }
78
79 inline int16_t byteswap(_In_ const int16_t value) { return byteswap((uint16_t)value); }
80 inline int32_t byteswap(_In_ const int32_t value) { return byteswap((uint32_t)value); }
81 inline int64_t byteswap(_In_ const int64_t value) { return byteswap((uint64_t)value); }
82
83 inline void byteswap(_Inout_ uint16_t* value) { assert(value); *value = byteswap(*value); }
84 inline void byteswap(_Inout_ uint32_t* value) { assert(value); *value = byteswap(*value); }
85 inline void byteswap(_Inout_ uint64_t* value) { assert(value); *value = byteswap(*value); }
86
87 inline void byteswap(_Inout_ int16_t* value) { byteswap((uint16_t*)value); }
88 inline void byteswap(_Inout_ int32_t* value) { byteswap((uint32_t*)value); }
89 inline void byteswap(_Inout_ int64_t* value) { byteswap((uint64_t*)value); }
90}
91
92#ifdef BIG_ENDIAN
93#define LE2HE(x) stdex::byteswap(x)
94#define BE2HE(x) (x)
95#define HE2LE(x) stdex::byteswap(x)
96#define HE2BE(x) (x)
97#else
98#define LE2HE(x) (x)
99#define BE2HE(x) stdex::byteswap(x)
100#define HE2LE(x) (x)
101#define HE2BE(x) stdex::byteswap(x)
102#endif