std::byteswap
Von de.cppreference.net
| Definiert in Header <bit>
|
||
template< class T >
constexpr T byteswap( T n ) noexcept;
|
(seit C++23) | |
Kehrt die Bytes im gegebenen Integer-Wert um n.
std::byteswap nimmt nur an der Überladungsauflösung teil, wenn T integral erfüllt, d.h. T ein Integer-Typ ist. Das Programm ist fehlerhaft, wenn T Padding-Bits hat.
Parameter
| n | - | Ganzzahlwert |
Rückgabewert
Ein ganzzahliger Wert vom Typ
T
dessen Objektdarstellung die Bytes der von
n
in umgekehrter Reihenfolge umfasst.
Hinweise
Diese Funktion ist nützlich für die Verarbeitung von Daten mit unterschiedlicher Bytereihenfolge.
| Feature-Test Makro | Wert | Std | Feature |
|---|---|---|---|
__cpp_lib_byteswap
|
202110L
|
(C++23) |
std::byteswap
|
Mögliche Implementierung
template<std::integral T> constexpr T byteswap(T value) noexcept { static_assert(std::has_unique_object_representations_v<T>, "T darf keine Padding-Bits enthalten"); auto value_representation = std::bit_cast<std::array<std::byte, sizeof(T)>>(value); std::ranges::reverse(value_representation); return std::bit_cast<T>(value_representation); } |
Beispiel
Diesen Code ausführen
#include <bit> #include <concepts> #include <cstdint> #include <iomanip> #include <iostream> template<std::integral T> void dump(T v, char term = '\n') { std::cout << std::hex << std::uppercase << std::setfill('0') << std::setw(sizeof(T) * 2) << v << " : "; for (std::size_t i{}; i != sizeof(T); ++i, v >>= 8) std::cout << std::setw(2) << static_cast<unsigned>(T(0xFF) & v) << ' '; std::cout << std::dec << term; } int main() { static_assert(std::byteswap('a') == 'a'); std::cout << "byteswap für U16:\n"; constexpr auto x = std::uint16_t(0xCAFE); dump(x); dump(std::byteswap(x)); std::cout << "\nbyteswap für U32:\n"; constexpr auto y = std::uint32_t(0xDEADBEEFu); dump(y); dump(std::byteswap(y)); std::cout << "\nbyteswap für U64:\n"; constexpr auto z = std::uint64_t{0x0123456789ABCDEFull}; dump(z); dump(std::byteswap(z)); }
Mögliche Ausgabe:
byteswap für U16: CAFE : FE CA FECA : CA FE byteswap für U32: DEADBEEF : EF BE AD DE EFBEADDE : DE AD BE EF byteswap für U64: 0123456789ABCDEF : EF CD AB 89 67 45 23 01 EFCDAB8967452301 : 01 23 45 67 89 AB CD EF
Siehe auch
(C++20) |
zeigt die Endianness von skalaren Typen an (enum) |
(C++20) |
berechnet das Ergebnis einer bitweisen Linksrotation (Funktionsschablone) |
(C++20) |
berechnet das Ergebnis einer bitweisen Rechtsrotation (Funktionsschablone) |
(C++29) |
kehrt die Bits in einer Ganzzahl um (Funktionsschablone) |