Related Tags

bitwise
binary
operator
type

# How to use std::byte in C++

std::byte is an enum class that was first introduced in C++17 and can be initialized using {} with any value from $0$ to $255$.

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:

## Operations

1. Left-shift (<<): 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;

1. Right-shift (>>): 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;

1. Logical operators: AND (&), OR (|), and XOR (^) bitwise operators can also be performed on 2-byteâ€‹ variables.

1 of 12

## Converting to an integer

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.

### Code

#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;
}

RELATED TAGS

bitwise
binary
operator
type