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
20#include "shambase/integer.hpp"
21
22namespace shambase {
23
36 inline bool is_little_endian() {
37 short int word = 0x0001;
38 char *byte = (char *) &word;
39 return (byte[0] ? 1 : 0);
40 }
41
50 template<class T>
51 inline void endian_swap(T &a) {
52
53 constexpr i32 sz = sizeof(a);
54
55 // Compute the number of byte swaps to perform, which is half of the size
56 // of the type if it is even, or (size - 1) / 2 if it is odd
57 auto constexpr lambd = []() {
58 if constexpr (sz % 2 == 0) {
59 return sz / 2;
60 } else {
61 return (sz - 1) / 2;
62 }
63 };
64
65 constexpr i32 steps = lambd();
66
67 u8 *bytes = (u8 *) &a;
68
69 // Perform byte swaps
70 for (i32 i = 0; i < steps; i++) {
71 xor_swap(bytes[i], bytes[sz - 1 - i]);
72 }
73 }
74
85 template<class T>
86 inline T get_endian_swap(T a) {
87 T ret = a;
89 return ret;
90 }
91
92} // 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:51
void throw_with_loc(std::string message, SourceLocation loc=SourceLocation{})
Throw an exception and append the source location to it.
T get_endian_swap(T a)
Return a copy of the input value with the endianness swapped.
Definition endian.hpp:86
bool is_little_endian()
Check if the CPU is in little endian.
Definition endian.hpp:36
void xor_swap(T &a, T &b)
swap two values using xor Source : https://graphics.stanford.edu/~seander/bithacks....
Definition integer.hpp:77