简体   繁体   English

使用uint8和uint16的cout << hex的行为

[英]Behavior of cout << hex with uint8 and uint16

I'm noticing that cout << hex is giving me strange results, and I cannot find anywhere that answers why. 我注意到cout << hex给了我奇怪的结果,我无法找到解决原因的地方。 What I am doing is simply assigning some values to both a uint8_t and uint16_t and then attempting to write them to stdout. 我正在做的只是为uint8_tuint16_t分配一些值,然后尝试将它们写入stdout。 When I run this: 当我运行这个:

uint8_t a = 0xab;
uint16_t b = 0x24de;
cout << hex << a << endl;
cout << hex << b << endl;

That I get the result: 我得到了结果:

$./a.out

24de
$

with no value displayed for the uint8_t. 没有显示uint8_t的值。 What could be causing this? 可能是什么导致了这个? I didn't think there wouldn't be a cout implementation for one type for not the other. 我认为不会有一种类型的cout实现而不是另一种类型。

std::uint8_t is an alias for unsigned char : std::uint8_tunsigned char的别名:

typedef unsigned char uint8_t;

So the overload of the inserter that takes a char& is chosen, and the ASCII representation of 0xab is written, which could technically vary by your operating system, as 0xab is in the range of Extended ASCII. 因此选择了char&的插入器的重载,并且写入了0xab的ASCII表示,这在技术上可能因操作系统而异,因为0xab在扩展ASCII的范围内。

You have to cast it to an integer: 你必须将它强制转换为整数:

std::cout << std::hex << static_cast<int>(a) << std::endl;

The other answers are correct about the reason. 其他答案是正确的。 The simplest fix is: 最简单的解决方法是:

cout << hex << +a << endl;

Demonstration: http://ideone.com/ZHHAHX 演示: http//ideone.com/ZHHAHX

It works because operands undergo integer promotion. 它的工作原理是操作数经过整数提升。

uint8_t is an alias for unsigned char . uint8_tunsigned char的别名。 You're essentially printing a character with the value 0xab , which might be an invalid character depending on your encoding. 您实际上是打印一个值为0xab的字符,根据您的编码,该字符可能是无效字符。

This would be solvable by casting it to another integer type, converting its value to a string in advance or writing some sort of a wrapper class that implements std::ostream& operator<<(std::ostream&, const ClassName&) . 这可以通过将其转换为另一个整数类型,将其值转换为字符串或编写某种实现std::ostream& operator<<(std::ostream&, const ClassName&)的包装类来解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM