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

Use case

Explicit byte type for binary data.

Explanation

std::byte is for raw bytes. Only bitwise ops are allowed (no arithmetic). Cleaner intent than char or uint8_t.

Code

#include <cstdint>
#include <iostream>

int main() {
  // https://en.wikipedia.org/wiki/Mach-O
  // 64-bit: 0xCF (0xFEEDFACF).
  // 32-bit: 0xCE (0xFEEDFACE).
  std::byte magic{0xCF};
  std::byte mask{0x0F};

  std::byte result = magic & mask;

  bool is64 = (result == std::byte{0x0F});

  std::cout << "64-bit: " << std::boolalpha << is64 << "\n";

  return 0;
}

View on GitHub.

Output

$ ./src/c++17/build/std-byte
64-bit: true