Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??
like image 733
louis.luo Avatar asked May 04 '12 15:05

louis.luo


People also ask

How to print unsigned char in hex?

// unsigned char declaration unsigned char status = 0x00; // printing out the value printf("status = (0x%02X)\n\r", (status |= 0xC0));

How do I print unsigned char buffer?

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++.

How do you print a hexadecimal with 2 digits?

printf("val = %02x\r\n", val); When using printf, %x means to format the value as hex. 02 means to pad the value with 0 s up to a length of 2 digits. If you would format 14 using just %x , it would print E instead of 0E .

How do you print hex value?

To print integer number in Hexadecimal format, "%x" or "%X" is used as format specifier in printf() statement. "%x" prints the value in Hexadecimal format with alphabets in lowercase (a-f). "%X" prints the value in Hexadecimal format with alphabets in uppercase (A-F).


2 Answers

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;
like image 111
JaredPar Avatar answered Sep 19 '22 06:09

JaredPar


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]) << " ";
}
like image 35
eigenfield Avatar answered Sep 22 '22 06:09

eigenfield