Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中打印无符号字符数组的十六进制值+;_C++_String_Hex_Std_Cout - Fatal编程技术网

C++ 在C+中打印无符号字符数组的十六进制值+;

C++ 在C+中打印无符号字符数组的十六进制值+;,c++,string,hex,std,cout,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;

我想使用
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;
由于某些原因,这无法打印出正确的十六进制值
str


如何才能
cout
正确的
str
hex
值?

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

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;
它对应于
str
中每个
无符号字符的
hex


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

十六进制 将str流的
basefield
格式标志设置为
hex

basefield
设置为
hex
时,插入流中的整数值以十六进制(即基数16)表示。对于输入流,设置此标志时,提取的值也应以十六进制表示

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