Back to results for “Modern C++”
C++ › Casting & Conversions

What is std::bit_cast (C++20)?

Advanced

Answer

std::bit_cast reinterprets the bit representation of one trivially-copyable type as another of the same size, safely and in a constexpr-friendly way—unlike reinterpret_cast or unions, it avoids undefined behavior and strict-aliasing issues. It's used for low-level conversions like reading a float's bits as an integer.
float f = 3.14f;
auto bits = std::bit_cast<std::uint32_t>(f); // safe bit reinterpretation
Real-world example std::bit_cast reads an IEEE float's raw bits for a hash without the UB of a reinterpret_cast.

Common follow-ups: How is it safer than reinterpret_cast? | What are its requirements?