如何在C ++中将无符号char []打印为HEX?

时间:2012-05-04 15:09:33

标签: c++ hex printf unsigned-char

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

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

2 个答案:

答案 0 :(得分:15)

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

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

由于您使用的是C ++,因此您应该考虑使用cout而不是printf(对于C ++来说,它更具惯用性。

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

答案 1 :(得分:2)

在 C++ 中

#include <iostream>
#include <iomanip>

unsigned char buf0[] = {4, 85, 250, 206};
for (int i = 0;i < sizeof buf0 / sizeof buf0[0]; i++) {
    std::cout << std::setfill('0') 
              << std::setw(2) 
              << std::uppercase 
              << std::hex << (0xFF & buf0[i]) << " ";
}