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

标签 c++ string hex std cout

我想使用 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 的正确十六进制值

如何计算 str 的正确十六进制值?

最佳答案

计算无符号字符的正确十六进制值,需要首先将其转换为整数。

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/

关于c++ - 在 C++ 中打印出 unsigned char 数组的十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30194803/

相关文章:

java - 为什么要将字符串转换为字符串?

c++ - 从十六进制字符串颜色到 RGB 颜色

c++ - 指向共享对象的指针在拥有它的不同对象中是不同的

c++ - 调用 execve() + 更改 PWD

c++ - some.exe : 0xC00000FD: Stack overflow 中 0x008437c7 处的第一次异常

php - 这段代码是不是太脆弱了?

python - 如何在 python 中拆分具有多个条件的字符串?

C - fwrite - 无法打开文件,因为它包含无效字符

java - Java读取文件的前10个字节

java - 使用 Java 配置系统环境以调用 JNI 调用