Search code examples
c++typesbytelanguage-features

Separate byte or int8 data type in c++


I have the following code:

#include <iostream>
using namespace std;

typedef uint8_t byte;

int main()
{
    byte x[5] = {0,1,2,3,4};

    byte* xptr = x;

    for (int i = 0; i < 5; ++i)
    {
        cout << "\n x[" << i
            << "] = " << *xptr
            << " at " << xptr;
        xptr = xptr + 1;
    }

    xptr = xptr - 5;

    cout << "\n\n\n";
}

the output contains strange characters as follows:

enter image description here

I expect this is because the underlying type of uint8_t is related to the char data type.

I know I can do some explicit type conversions to get it work as follows:

cout << "\n x[" << i
    << "] = " << (int)*xptr
    << " at " << (void*)xptr;

also, I know I can make class to handle it myself.

enter image description here

However, I prefer not to use type conversion or make a special class if possible.

I went through the Internet and I got this on StackOverflow, but it did not help.

So, is there a native way to have an 8 bit integer type on C++ that acts exactly like int and short with all standard libraries? or this is just one of the countless C++ unconvincing* feature absence?

*at least to me.


Solution

  • uint8_t and int8_t are your real 8-bit integers on C++. But because they are typedefs over chars (if they exist at all, it's not guaranteed), they are interpreted and treated as characters by the standard library. Unfortunately, you'll just have to use a cast.

    Side note: you don't need to use pointers here, use array indices:

    for (int i = 0; i < 5; ++i)
    {
        cout << "\n x[" << i
            << "] = " << (int)x[i]
            << " at " << hex << &x[i] << dec;
    }
    

    Side note #2: C++17 will introduce a std::byte type, but it is just a strange wrapper around unsigned char using enum class. It only implements bitwise operators and conversion functions to and from integer types, so it is not what you're looking for.