std::byteswap
ja.cppreference.net から
| ヘッダ <bit>
|
||
template< class T >
constexpr T byteswap( T n ) noexcept;
|
で定義 (C++23 以降) | |
指定された整数値のバイト順を反転します n。
std::byteswap は、T が integral を満たす場合にのみオーバーロード解決に参加します。すなわち、T は整数型です。T にパディングビットがある場合、プログラムは ill-formed です。
パラメータ
| n | - | 整数値 |
戻り値
型
T
の整数値で、そのオブジェクト表現が
n
のオブジェクト表現のバイトを逆順に並べたものから構成される値。
注記
この関数は、異なるエンディアンのデータを処理する際に有用です。
| 機能テスト マクロ | 値 | 標準 | 機能 |
|---|---|---|---|
__cpp_lib_byteswap
|
202110L
|
(C++23) |
std::byteswap
|
実装例
template<std::integral T> constexpr T byteswap(T value) noexcept { static_assert(std::has_unique_object_representations_v<T>, "T may not have padding bits"); 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); } |
例
このコードを実行
#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 for U16:\n"; constexpr auto x = std::uint16_t(0xCAFE); dump(x); dump(std::byteswap(x)); std::cout << "\nbyteswap for U32:\n"; constexpr auto y = std::uint32_t(0xDEADBEEFu); dump(y); dump(std::byteswap(y)); std::cout << "\nbyteswap for U64:\n"; constexpr auto z = std::uint64_t{0x0123456789ABCDEFull}; dump(z); dump(std::byteswap(z)); }
出力例:
byteswap for U16: CAFE : FE CA FECA : CA FE byteswap for U32: DEADBEEF : EF BE AD DE EFBEADDE : DE AD BE EF byteswap for U64: 0123456789ABCDEF : EF CD AB 89 67 45 23 01 EFCDAB8967452301 : 01 23 45 67 89 AB CD EF
関連項目
(C++20) |
スカラー型のエンディアンを示す (列挙型) |
(C++20) |
ビット単位の左ローテーションの結果を計算する (関数テンプレート) |
(C++20) |
ビット単位の右ローテーションの結果を計算する (関数テンプレート) |
(C++29) |
整数のビットを反転する (関数テンプレート) |