How to work with uint8_t instead of char?

I want to understand the situation related to uint8_t vs char, portability, bit manipulation, best practices, state of affairs, etc. Do you know a good read on this topic?

I want to do byte-IO. But, of course, char has a more complex and subtle definition than uint8_t; which, I believe, was one of the reasons for introducing the stdint header.

However, I had problems using uint8_t in several cases. A few months ago once, because iostreams are not defined for uint8_t. Isn't there a C ++ library that does true-byte-by-IO, i.e. read and write uint8_t? If not, I assume there is no demand for it. Why?

My last headache is related to the failure to compile this code:

uint8_t read(decltype(cin) & s)
{
    char c;
    s.get(c);
    return reinterpret_cast<uint8_t>(c);
}

error: invalid cast from type 'char' to type 'uint8_t {aka unsigned char}'

Why a mistake? How to do it?

+4
2

, , - :

  • API, 8 ,
  • - char, signed char unsigned char -
  • unsigned char uint8_t .

:

bool read_one_byte(std::istream & is, uint8_t * out)
{
    unsigned char x;    // a "byte" on your system 
    if (is.get(reinterpret_cast<char *>(&x)))
    {
        *out = x;
        return true;
    }
    return false;
}

bool write_one_byte(std::ostream & os, uint8_t val)
{
    unsigned char x = val;
    return os.write(reinterpret_cast<char const *>(&x), 1);
}

: 1 , uint8_t unsigned char . 2 , - iostream unsigned char, char s.

is.read(reinterpret_cast<char *>(&x), 1) is.get() . ( read , 1, gcount() , .)

, -. ​​ .

+2

, iostreams uint8_t.

uint8_t typedef unsigned char. , , , .

uint8_t read(decltype(cin) & s)
{
    char c;
    s.get(c);
    return reinterpret_cast<uint8_t>(c);
}

decltype(cin) std::istream , . return - ; a char unsigned char .

, iostreams uint8_t.

. uint8_t , , , , . → unsigned char. :

uint8_t read(istream& s)
{
    return s.get();
}

unsigned char char , reinterpret_cast char unsigned char* .

, Kerreks.

0

All Articles