我想在 C++ 中使用无符号的 8 位变量。 Either unsigned char
or uint8_t
do the trick as far as the arithmetic is concerned (which is expected, since AFAIK uint8_t
is just an alias for unsigned char
,或者调试器呈现它。
问题是,如果我在 C++ 中使用 ostream 打印出变量,它会将其视为 char。如果我有:
unsigned char a = 0;
unsigned char b = 0xff;
cout << "a is " << hex << a <<"; b is " << hex << b << endl;
那么输出是:
a is ^@; b is 377
代替
a is 0; b is ff
我尝试使用 uint8_t
,但正如我之前提到的,它的类型定义为 unsigned char
,所以它也是一样的。如何正确打印我的变量?
编辑: 我在我的代码中的很多地方都这样做。有什么办法可以做到这一点 ,而无需 每次我想打印时都转换为 int
?
原文由 Nathan Fellman 发布,翻译遵循 CC BY-SA 4.0 许可协议
我建议使用以下技术:
它写起来很短,与原始解决方案具有相同的效率,并且可以让您选择使用“原始”字符输出。而且它是类型安全的(不使用“邪恶”宏:-))