为什么未签名的char不能正确显示十六进制值 [英] Why can't an unsigned char properly display a hex value
问题描述
我正在尝试创建一个1字节值的数组,使用无符号字符来保存值.
I am trying to create an array of 1 byte values, using unsigned chars to hold the values.
我的代码如下:
unsigned char state[4][4] = { {0xd4, 0xe0, 0xb8, 0x1e},
{0xbf, 0xb4, 0x41, 0x27},
{0x5d, 0x52, 0x11, 0x98},
{0x30, 0xae, 0xf1, 0xe5}};
每个值都是2个十六进制数字,表示一个字节.但是,当我尝试使用
Where each value is 2 hex digits which makes a byte. However, when I attempt to print the array out using
cout << "\nInitial State \n------------------------------------------------------\n";
for(int x = 0; x < 4; x++)
{
for(int y = 0; y < 4; y++)
cout << hex << setw(2) << setfill('0') << state[x][y] << " ";
cout << "\n";
}
我没有得到十六进制值,而是奇怪的符号
I don't get the hex value, but rather weird symbols
Initial State
---------------------
0Ô 0à 0¸ 0
0¿ 0´ 0A 0'
0] 0R 0 0˜
00 0® 0ñ 0å
我知道0来自set(w)和setfill('0'),但我不明白为什么它没有显示正确的值.但是,如果将状态设置为无符号长,则可以得到正确的值.
I understand the 0s come from set(w) and setfill('0') but I don't understand why it isn't showing the proper values. However, if I make the state an unsigned long, I then get the proper values.
所以我很困惑.如果一个char恰好持有一个字节,为什么char不能将该字节显示为十六进制值?
So I'm confused. If a char holds exactly one byte, why can't the char display the byte as a hex value?
推荐答案
cout
专门用于将 char
类型输出为字符而不是数字.这也适用于未签名的字符.通过强制转换为 unsigned int
.
cout
is specialized to output the char
type as a character, not a number. That goes for unsigned chars too. You get around it by casting to an unsigned int
.
cout << hex << setw(2) << setfill('0') << static_cast<unsigned int>(state[x][y]) << " ";
这篇关于为什么未签名的char不能正确显示十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!