Friday, 5 February 2021

Print a Char as a Number

 When you are interested in the number of bits in your  integer such as in embedded programming, you often find yourself trying to print an 8 bit byte and it appears as the character rather than the number.


uint8_t byValue{65};
std::cout << "Value:" << byValue << std::endl;
// Result
//     Value:A

This occurs because uint8_t acts like a C-style char.


You can overcome this by casting it to a larger integer type:
uint8_t byValue{65};
std::cout << "Value:" << static_cast<uint32_t>(byValue);
// Result
// 
    Value:65

But that isn't so readable.


Alternatively, you can promote it to an int value by using unary addition, add 0 to keep the same value.

uint8_t byValue{65};
std::cout << "Value:" << byValue + 0 << std::endl;
// Result
//     Value:65 

I find this easier to read.


No comments:

Post a Comment