[c++] Is there 'byte' data type in C++?

If exists is there header file to include?

This code give compilation error:

#include <iostream>

using namespace std;

int main()
{
    byte b = 2;

    cout << b << endl;

    return 0;
}

This question is related to c++

The answer is


Using C++11 there is a nice version for a manually defined byte type:

enum class byte : std::uint8_t {};

That's at least what the GSL does.

Starting with C++17 (almost) this very version is defined in the standard as std::byte (thanks Neil Macintosh for both).


Yes, there is std::byte (defined in <cstddef>).

C++ 17 introduced it.


if you are using windows, in WinDef.h you have:

typedef unsigned char BYTE;

There's also byte_lite, compatible with C++98, C++11 and later.


No, there is no type called "byte" in C++. What you want instead is unsigned char (or, if you need exactly 8 bits, uint8_t from <cstdint>, since C++11). Note that char is not necessarily an accurate alternative, as it means signed char on some compilers and unsigned char on others.


namespace std
{
  // define std::byte
  enum class byte : unsigned char {};

};

This if your C++ version does not have std::byte will define a byte type in namespace std. Normally you don't want to add things to std, but in this case it is a standard thing that is missing.

std::byte from the STL does much more operations.


No, but since C++11 there is [u]int8_t.