在 C++ 中打印出 unsigned char 数组的十六进制值

Printing out the hex vale of an unsigned char array in C++

我想使用 cout 函数打印出 unsigned char 数组的 hex 值。

最明显的方法如下所示。

unsigned char str[] = "foo bar baz\n";

for(unsigned short int i = 0; i < sizeof(str); i++){
  std::cout << std::hex << str[i] << std::dec << ' ';
}

std::cout << std::endl;

令人惊讶的是,这会输出以下字符串:

foo bar baz

出于某种原因,这不会打印出 str

的正确十六进制值

如何 cout str 的正确 hex 值?

cout unsigned char 的正确十六进制值,需要先将其转换为整数。

unsigned char str[] = "foo bar baz\n";

for(unsigned short int i = 0; i < sizeof(str); i++){
  std::cout << std::hex << (int) str[i] << std::dec << ' ';
}

std::cout << std::endl;

给出以下输出。

66 6f 6f 20 62 61 72 20 62 61 7a 00

对应于str中每个unsigned charhex值。


可以在以下 std::hex 文档中找到对此的解释。

std::hex

Sets the basefield format flag for the str stream to hex.

When basefield is set to hex, integer values inserted into the stream are expressed in hexadecimal base (i.e., radix 16). For input streams, extracted values are also expected to be expressed in hexadecimal base when this flag is set.

http://www.cplusplus.com/reference/ios/hex/