cout的行为<< uint8和uint16的十六进制 [英] Behavior of cout << hex with uint8 and uint16

查看:492
本文介绍了cout的行为<< uint8和uint16的十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到cout << hex给了我奇怪的结果,而我找不到任何能回答原因的地方.我正在做的只是将一些值同时分配给uint8_tuint16_t,然后尝试将它们写入stdout.当我运行此命令时:

I'm noticing that cout << hex is giving me strange results, and I cannot find anywhere that answers why. 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. When I run this:

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

我得到结果:

$./a.out

24de
$

,未显示uint8_t的值.是什么原因造成的?我不认为不会为一种类型提供cout实现,而不是为另一种类型实现.

with no value displayed for the 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.

推荐答案

std::uint8_tunsigned char的别名:

typedef unsigned char uint8_t;

因此选择了使用char&的插入程序的重载,并编写了0xab的ASCII表示形式,由于0xab在扩展ASCII范围内,因此在技术上可能会因操作系统而异.

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.

您必须将其转换为整数:

You have to cast it to an integer:

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

这篇关于cout的行为&lt;&lt; uint8和uint16的十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆