Question

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??
Was it helpful?

Solution

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 char values individually as hex values.

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 cout instead of printf (it's more idiomatic for C++.

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

OTHER TIPS

In 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]) << " ";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top