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::bit_cast

Use case

Safer reinterpretation of bits.

Explanation

std::bit_cast copies bits to a new object. Also constexpr-friendly and catches size mismatches at compile-time.

Code

#include <array>
#include <bit>
#include <cstdint>
#include <iostream>

int main() {
  // https://en.wikipedia.org/wiki/Mach-O
  std::array<uint8_t, 4> bytes = {0xCF, 0xFA, 0xED, 0xFE};

  uint32_t magic = std::bit_cast<uint32_t>(bytes);

  std::cout << "Magic: 0x" << std::hex << magic << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++20/build/std-bit_cast
Magic: 0xfeedfacf