std::byteswap
來自 cppreference.com
定義於標頭檔案 <bit> |
||
template< class T > constexpr T byteswap( T n ) noexcept; |
(C++23 起) | |
反轉給定整數值 n 中的位元組。
std::byteswap
僅在 T
滿足 integral
(即 T
是整數型別)時參與過載決議。如果 T
具有填充位,則程式格式錯誤。
目錄 |
[編輯] 引數
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) |
計算位右旋的結果 (函式模板) |