Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

std::byteswap

Use case

Endianness conversion.

Explanation

Before C++23: builtins. Now portable std::byteswap.

Code

#include <bit>
#include <cstdint>
#include <print>

int main() {
  // https://en.wikipedia.org/wiki/Mach-O
  uint32_t beMagic = 0xFEEDFACF;

  uint32_t leMagic = std::byteswap(beMagic);

  std::println("BE: {:#x}", beMagic);
  std::println("LE: {:#x}", leMagic);

  return 0;
}

View on GitHub.

Output

$ ./src/c++23/build/std-byteswap
BE: 0xfeedfacf
LE: 0xcffaedfe