如何在 C++ 中将 unsigned char[] 打印为 HEX?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10451493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:04:38  来源:igfitidea点击:

How to print unsigned char[] as HEX in C++?

c++hexprintfunsigned-char

提问by louis.luo

I would like to print the following hashed data. How should I do it?

我想打印以下散列数据。我该怎么做?

unsigned char hashedChars[32];
SHA256((const unsigned char*)data.c_str(),
       data.length(), 
       hashedChars);
printf("hashedChars: %X\n", hashedChars);  // doesn't seem to work??

回答by JaredPar

The hex format specifier is expecting a single integer value but you're providing instead an array of char. What you need to do is print out the charvalues individually as hex values.

十六进制格式说明符需要一个整数值,但您提供的是一个char. 您需要做的是将char值单独打印为十六进制值。

printf("hashedChars: ");
for (int i = 0; i < 32; i++) {
  printf("%x", hashedChars[i]);
}
printf("\n");

Since you are using C++ though you should consider using coutinstead of printf(it's more idiomatic for C++.

由于您使用的是 C++,但您应该考虑使用cout而不是printf(它更符合 C++ 的习惯。

cout << "hashedChars: ";
for (int i = 0; i < 32; i++) {
  cout << hex << hashedChars[i];
}
cout << endl;