Std :: cout deals with uint8_t as character

If I run this code:

std::cout << static_cast<uint8_t>(65);

He will output:

AND

What is the ASCII equivalent of 65. This is because it is uint8_tsimply defined as:

typedef unsigned char uint8_t;
  • Is this the standard?

  • Shouldn't there be a better way to determine uint8_twhich is guaranteed to be treated as a number, not a character?

I cannot understand the logic that if I want to print the value of a variable uint8_t, it will be printed as a character.

PS I am using MSVS 2013.

+4
source share
3 answers

Is this behavior standard?

, uint8_t typedef unsigned char, , std::ostream unsigned char .

uint8_t, , ?

++ . , sizeof(), 1, char, signed char unsigned char. , bool, bool 1, ,

int main()
{
    bool foo = 42;
    std::cout << foo << '\n';
}

1, 42, , true 1, .

, , -, cast


++ 17 std::byte, enum class byte : unsigned char {};. , , . , enum class, . , , . , , unsigned char. -

std::ostream& operator <<(std::ostream& os, std::byte b)
{
    return os << std::to_integer<unsigned int>(b);
}

std::istream& operator <<(std::istream& is, std::byte& b)
{
    unsigned int temp;
    is >> temp;
    b = std::byte{b};
    return is;
}

int main()
{
    std::byte foo{10};
    std::cout << foo;
}
+3

, ostream unsigned char, unsigned char - typedef uint8_t .

§27.7.3.1 [output.streams.ostream] :

template<class traits>
basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>&, unsigned char);

, , uint8_t unsigned char . , , 1 .

 std::cout << std::boolalpha << std::is_same<uint8_t, unsigned char>::value << std::endl; // prints true

, , unsigned char ( ). , uint16_t , :

uint8_t a = 65;
std::cout << static_cast<uint16_t>(a) << std::endl; // prints 65

+3

, .

uint8_t typedef char unsigned char. (, , ).

, , (short, int, long ..). , 128- .

" C", C ++ .

, . + .

, , uint8_t , , , .

+3
source

Source: https://habr.com/ru/post/1652467/


All Articles