General Purpose library for Freestanding C++ and POSIX systems
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

56 lines
876 B

#pragma once
#include "gp/containers/array.hpp"
#include <bit>
#include <stddef.h>
#include <stdint.h>
namespace gp {
using endian = std::endian;
template <typename T>
T swap_endian(T value) {
union {
T v;
uint8_t u8[sizeof(T)];
} src, dest;
src.v = value;
for (size_t idx = 0;idx<sizeof(T);idx++) {
dest.u8[idx] = src.u8[sizeof(T)-idx-1];
}
return dest.v;
}
template<typename T, endian mode = endian::big>
struct endian_wrapper {
union {
T value;
gp::array<uint8_t, sizeof(T)> bytes;
};
endian_wrapper() {}
endian_wrapper(T v)
: value{mode == endian::native ? v : swap_endian(v)} {}
endian_wrapper(endian_wrapper& v)
: value{v.value} {}
endian_wrapper& operator=(T p) {
value = mode == endian::native ? p : swap_endian(p);
return *this;
}
operator T() {
return mode == endian::native ? value : swap_endian(value);
}
};
}