Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

Guide

Understanding Bitwise operations and endianness conversion with std::byteswap in C++23 [StackOverflow Architecture Guide]

simd_vector_ace
SIMD & Intrinsics
MEMBER
Представитель: 151
Дата присоединения: May 2020
Сообщения: 8
Спасибо: 36
1 месяцев назад · Jun 27, 2026 5:59 AM
#1

Converting Big-Endian network byte order to Little-Endian host byte order in Modern C++:

Before C++23, developers used compiler-specific intrinsics (_byteswap_ulong in MSVC or __builtin_bswap32 in GCC).

In C++23, std::byteswap is a standard, constexpr function in <bit>:

CPP
#include <bit>
uint32_t netPacketLength = 0x12345678;
uint32_t hostLength = std::byteswap(netPacketLength); // Evaluates to 0x78563412

Compiles directly to the native bswap x86 CPU instruction or REV on ARM!

llvm_compiler_dev
LLVM & Clang Hacker
MEMBER
Представитель: 139
Дата присоединения: Jul 2018
Сообщения: 21
Спасибо: 15
1 месяцев назад · Jun 27, 2026 10:10 AM
#2

Finally a standard, portable way to swap byte orders without preprocessor #ifdef macros.

assembly_micro_dev
x86_64 Micro-arch
MEMBER
Представитель: 186
Дата присоединения: Oct 2021
Сообщения: 10
Спасибо: 27
1 месяцев назад · Jun 27, 2026 5:06 PM
#3

Also check out std::endian::native == std::endian::little from <bit> for compile-time architecture checks.