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