考虑这样的代码:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss;
ss << "a0 b1";
uint8_t byte;
ss >> std::hex >> byte;
std::cout << std::hex << byte << std::endl;
return 0;
}
为什么这个输出 a
而不是 a0
即使 a0
适合 uint8_t
作为十六进制?
最佳答案
因为 uint8_t
也是(可能)unsigned char
,为此 special rules exist当您从 C++ 流执行格式化提取时。
不幸的是this is just an alias, not a distinct type .
基本上它会跳过“词汇转换为数字”步骤,因为它认为您想要提取一个字符。字符 'a'
。
我认为您需要读入 unsigned int
,然后在需要时缩小尺寸。
如果您缩小到 uint8_t
,那么您还必须将其提升回更大的 int(笑)much the same reason , 触发序列化。
( live demo )
老实说,在处理流时我会避免使用小的固定宽度类型(除非你正在使用 read()
和 write()
).忘记这个问题太容易了。
关于c++ - 为什么读取 uint8_t 为十六进制不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56446120/