Ch2.20: ::std::byte

Overview

::std::byte is a type that represents a single byte of data. Unlike char or unsigned char, ::std::byte is not a character type and cannot be used for text. It is simply a small, strongly typed unit of storage.

In this chapter, you will learn:

1. What is ::std::byte?

::std::byte is an enumeration-like type that represents a single byte. It does not store characters or numbers directly. Instead, it stores raw byte values.


::std::byte b{};

This creates a ::std::byte with value zero.

2. Initializing ::std::byte

You can initialize a ::std::byte using ::std::byte{} or by converting from an integer.


::std::byte a{};                 // zero
::std::byte b{static_cast<unsigned char>(42)};

Note: You must use an explicit cast when converting from an integer. This prevents accidental misuse.

3. Converting ::std::byte to integers

To convert a ::std::byte back to an integer, use ::std::to_integer.


::std::byte b{static_cast<unsigned char>(7)};
unsigned int x = ::std::to_integer<unsigned int>(b);

This extracts the numeric value stored in the byte.

4. Why does ::std::byte exist?

Before ::std::byte existed, programmers often used unsigned char to represent raw bytes. But unsigned char is still a character type, which can lead to confusion.

::std::byte solves this by providing a type that:

5. Operations on ::std::byte

::std::byte supports bitwise operations such as:


::std::byte b{static_cast<unsigned char>(1)};
b = b << 2;   // shift left

These operations treat the byte as raw bits, not as a number.

Key takeaways