C++ Basics: Copy Object Representation with std::bit_cast
Distinguish copying an integer representation from converting its numeric value.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as bit-cast-byte-roundtrip-demo.cpp:
#include <array>
#include <bit>
#include <climits>
#include <cstdint>
#include <iostream>
int main()
{
static_assert(CHAR_BIT == 8);
using ByteStorage = std::array<unsigned char, sizeof(std::uint32_t)>;
static_assert(sizeof(ByteStorage) == sizeof(std::uint32_t));
const std::uint32_t original = 0x1234;
const ByteStorage representation = std::bit_cast<ByteStorage>(original);
const auto restored = std::bit_cast<std::uint32_t>(representation);
const auto narrowed = static_cast<unsigned char>(original);
std::cout << "Stored bytes: " << representation.size() << '\n';
std::cout << std::boolalpha << "Round trip equal: " << (restored == original) << '\n';
std::cout << "Numeric conversion: " << static_cast<unsigned int>(narrowed) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic bit-cast-byte-roundtrip-demo.cpp -o bit-cast-byte-roundtrip-demo &&
./bit-cast-byte-roundtrip-demoObserved output:
Stored bytes: 4
Round trip equal: true
Numeric conversion: 52Read the result
The byte array preserves the integer representation and can reconstruct the original value. Converting to an unsigned character instead computes the value modulo 256, leaving 52. Neither operation accesses an object through an incompatible pointer.
Apply it carefully
bit_cast requires equal sizes and trivially copyable types. This example explicitly requires eight-bit bytes and a uint32_t implementation; it prints no byte ordering, so little- and big-endian systems can produce the same output. A representation copy is not a portable network encoding. Do not generalize this round trip to arbitrary padded objects, pointers, or invalid destination representations.
The C++ working draft describes the relevant rules. This example uses C++20 facilities; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- bit-cast-byte-roundtrip-demo.cpp bit-cast-byte-roundtrip-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.