Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::bit_cast — creating a value from a bit representation

std::bit_cast<To>(from) creates a new object from the source object's bits. Both types must have equal size and be trivially copyable; this is neither a numeric conversion nor access to the source through an alias.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <bit>
template<class To, class From>
constexpr To std::bit_cast(const From& from) noexcept;

std::bit_cast<To>(from)

std::bit_cast from <bit> returns a new object of type To. Its value-representation bits correspond to the object-representation bits of from. It performs no numeric conversion and creates no reference to the source. From is normally deduced.

The call requires sizeof(To) == sizeof(From) and both types to be trivially copyable. These conditions alone do not make arbitrary bit patterns safe: the result must represent a valid destination value. Result padding bits are unspecified; avoid uninitialized data and transferring padding into value bits.

The function is noexcept. Its constexpr declaration does not mean every call can be evaluated at compile time. The example uses unsigned char and std::byte to demonstrate such a conversion without assumptions about byte order or floating-point format.

This entry targets C++23. The linked document is an evolving working draft, not a frozen C++23 edition; its newer rules must not automatically be applied to C++23. A repository compiler flag does not attest production runtime compatibility.

Examples

#include <bit>
#include <cstddef>
#include <iostream>

int main() {
    constexpr unsigned char source = 42;
    constexpr auto bits = std::bit_cast<std::byte>(source);
    constexpr auto restored = std::bit_cast<unsigned char>(bits);
    static_assert(restored == source);
    std::cout << static_cast<unsigned int>(restored) << '\n';
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources