[TAG] C++'s cout and hexadecimal output
René Pfeiffer
lynx at luchs.at
Thu Jun 26 03:16:04 MSD 2008
Hello, Gang!
I am trying to compute a SHA1 hash inside a C++ program without linking
to additional libraries. There are some SHA1 code snippets around and
they seem to work. So far so good. In order to compare SHA1 sums it's
nice to have them in hexadecimal representation. The SHA1 code I used
holds the sum in a byte array which is basically an array of unsigned
chars. Creating hexadecimal output can be done as follows:
// Filename: hex_output.cc - cout test firing range
#include <iomanip>
#include <ios>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv) {
unsigned char array[10];
unsigned short i;
// An array with a French accent (sorry, SCNR)
array[0] array[1] array[2] array[3] array[4] array[5] array[6] array[7] array[8] array[9] for( i=0; i<10; i++) {
cout << hex << setfill('0') << setw(2) << nouppercase << array[i];
}
cout << endl << endl;
return(0);
}
Unfortunately this outputs: 0A0L0L0o0 0O0r0l0d0!
As soon as I change the cout line to
cout << hex << setfill('0') << setw(2) << nouppercase << (unsigned short)array[i];
it works and produces: 414c4c6f204f726c6421
It's late and I still lack my good night coffee, but why is that? I
didn't expect this behaviour.
Best,
Ren?.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://lists.linuxgazette.net/mailman/private/tag/attachments/20080626/5013e451/attachment.pgp
More information about the TAG
mailing list