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:
- what
::std::byteis - how to create and use
::std::bytevalues - how to convert between
::std::byteand integers - why
::std::byteexists
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:
- is clearly meant for raw data
- cannot be mistaken for a character
- does not behave like a number
- supports only bitwise operations
5. Operations on ::std::byte
::std::byte supports bitwise operations such as:
|(bitwise OR)&(bitwise AND)^(bitwise XOR)<<(shift left)>>(shift right)
::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
::std::byteis a type representing a single byte.- It is not a character type and not a number.
- It requires explicit conversion to and from integers.
- It supports only bitwise operations.
- It is useful when you want to express “this is raw data”.