Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
endian.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
18
20#include "shambase/integer.hpp"
21#include <bit>
22
23namespace shambase {
24
30 constexpr bool is_little_endian() noexcept {
31 return std::endian::native == std::endian::little;
32 }
33
42 template<class T>
43 inline void endian_swap(T &a) {
44
45 constexpr i32 sz = sizeof(a);
46
47 // Compute the number of byte swaps to perform, which is half of the size
48 // of the type if it is even, or (size - 1) / 2 if it is odd
49 auto constexpr lambd = []() {
50 if constexpr (sz % 2 == 0) {
51 return sz / 2;
52 } else {
53 return (sz - 1) / 2;
54 }
55 };
56
57 constexpr i32 steps = lambd();
58
59 u8 *bytes = (u8 *) &a;
60
61 // Perform byte swaps
62 for (i32 i = 0; i < steps; i++) {
63 xor_swap(bytes[i], bytes[sz - 1 - i]);
64 }
65 }
66
77 template<class T>
78 inline T get_endian_swap(T a) {
79 T ret = a;
80 endian_swap(ret);
81 return ret;
82 }
83
84} // namespace shambase
std::uint8_t u8
8 bit unsigned integer
std::int32_t i32
32 bit integer
namespace for basic c++ utilities
void endian_swap(T &a)
Swap the endianness of the input value.
Definition endian.hpp:43
T get_endian_swap(T a)
Return a copy of the input value with the endianness swapped.
Definition endian.hpp:78
void xor_swap(T &a, T &b)
swap two values using xor Source : https://graphics.stanford.edu/~seander/bithacks....
Definition integer.hpp:77
constexpr bool is_little_endian() noexcept
Check if the CPU is in little endian.
Definition endian.hpp:30