Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::byte — a byte without numeric semantics

std::byte from <cstddef> represents raw byte data. It is a distinct enumeration type, not an alias for unsigned char. It supports bitwise operations, but not ordinary arithmetic or implicit conversions to integer types.

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

Syntax

#include <cstddef>

std::byte b{0x2A};
auto masked = b & std::byte{0x0F};
auto value = std::to_integer<unsigned int>(masked);

std::byte is declared in <cstddef> as enum class byte : unsigned char {}; in namespace std. Use it when a value represents raw byte data rather than a text character or a number intended for calculation. It is a distinct type, not an alias for unsigned char.

The declaration std::byte b{0x2A}; directly initializes a byte from an integer. This initialization requires a non-narrowing conversion to the underlying type. The declaration std::byte b = 42; is invalid: there is no implicit conversion from an integer. Convert back explicitly, for example with std::to_integer<unsigned int>(b); its template argument must be an integral type.

The binary operators &, |, ^, <<, and >> have corresponding compound assignment operators: &=, |=, ^=, <<=, and >>=. The unary bitwise complement operator ~ is also supported, but has no compound assignment counterpart. All these operations are constexpr and noexcept. A shift count must have an integral type. Ordinary arithmetic such as b + b or ++b is not supported.

The example applies the mask 0x0F to 0x2A, leaving the value 10. Before printing, the result is converted using std::to_integer<unsigned int>; the library provides no direct insertion operator for writing std::byte to std::cout.

Examples

#include <cstddef>
#include <iostream>

int main() {
    constexpr std::byte value{0x2A};
    constexpr std::byte mask{0x0F};
    constexpr std::byte low = value & mask;
    static_assert(std::to_integer<unsigned int>(low) == 10u);

    std::cout << std::to_integer<unsigned int>(low) << '\n';
}

Result

10

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