1

I have the following code:

#include <iostream>

int main(void)
{
unsigned long x=2;
std::uint8_t y=static_cast<std::uint8_t>(x);
std::cout<<"aa:"<<x<<std::endl;
std::cout<<"bb:"<<y<<std::endl;
bool a = x==2;
bool b = y==2;
std::cout<<a<<std::endl;
std::cout<<b<<std::endl;

 return 0;
} 

When i run it i get this output:

aa:2
bb:(some weird ascii character)
1
1

What confuses me is that while I am casting an unsigned long (x) to a uint8_t, when I try to print to output the actual output I notice some weird ascii character for the output of y, instead of the value 2 I would have expected. Yet when I do a boolean comparison with 2, both compare to true. Why is it that I am not able to properly print to standard output an unsigned long cast to uint8_t? What am I misunderstanding? Are casts from unsigned long to uint8_t not permitted in C++ even for small values? Thanks

astrophobia
  • 839
  • 6
  • 13
  • 2
    uint8_t could also be called "char" on many systems, and when you print it, you get the ascii character 2. It still has the exact same value, but is displayed differently. To further illustrate, try x=65, and note that it is displayed differently as a char ('A'), but it still has the same value. – Kenny Ostrom Jan 24 '19 at 21:10
  • @Nathan He he he, I didn't see that in first place when reading the question. – πάντα ῥεῖ Jan 24 '19 at 21:30
  • FWIW, If you have C++17 you can use `std::byte` instead of `uint8_t`. It doesn't have a output operator defined for it so it would fail to compile and force you to do that cast if you want to output it. – NathanOliver Jan 24 '19 at 21:33

0 Answers0