std::byte is an enum class that was first introduced in C++17 and can be initialized using {}
with any value from to .
Make sure to include the
cstddef
header file.
#include <cstddef>
// Initializing a 'byte' variable:
std::byte x{2};
Only the following bitwise operations can be performed on a byte variable:
<<
): Shifts all digits of a binary number to the left by the specified number of steps.Shifting a binary number one-step to the left equates to multiplying it by 2.
std::byte x{3};
// Multiply 'x' by 4 and store the result back in 'x':
x <<= 2;
>>
): Shifts all digits of a binary number to the right by the specified number of steps.Shifting a binary number one-step to the right equates to dividing it by 2.
std::byte x{32};
// Divide 'x' by 8 and store the result back in 'x':
x >>= 3;
&
), OR (|
), and XOR (^
) bitwise operators can also be performed on 2-byte variables.A byte can be converted to a signed or unsigned integer using the to_integer<type>
function. This function is safer than a normal cast because it prevents a byte from being converted into a float
.
#include <iostream>#include <cstddef>using namespace std;int main() {byte x{20};// Multiply 'x' by 2 => x = 20 * 2 = 40:x <<= 1;// Divide 'x' by 4 => x = 40 / 4 = 10:x >>= 2;cout << "x = " << to_integer<int>(x) << endl;return 0;}
Free Resources