0

I have a char[32] that consist of ASCII characters, some of which may be non printable characters, however, they are all in valid range of 0 to 255.

Let's say, it contains these numbers: { 9A 2E 5C 66 26 3D 5A 88 76 26 F1 09 B5 32 DE 10 91 3E 68 2F EA 7B C9 52 66 23 9D 77 16 BB C9 42 }

I'd like to print out or store in std::string as "9A2E5C66263D5A887626F109B532DE10913E682FEA7BC95266239D7716BBC942", however, if I print it out using printf or sprintf, it will yield the ASCII representative of each number, and instead it will print out "ö.\f&=Zàv&Ò µ2fië>h/Í{…Rf#ùwª…B", which is the correct ASCII character representation, since: ö = 9a, . = 2e, ...

How do I reliably get the string representation of the hex numbers? ie: I'd expect a char[64] which contains "9A2E5C66263D5A887626F109B532DE10913E682FEA7BC95266239D7716BBC942" instead.

Thanks!

4

3 に答える 3

0

I tried:

  char szStringRep[64];
  for ( int i = 0; i < 32; i++ ) {
    sprintf( &szStringRep[i*2], "%x", szHash[i] );
  }

it works as intended, but if it encountered a < 0x10 number, it will null terminated as it is printing 0

于 2013-03-17T18:34:24.243 に答える
0

You can encode your string to another system like Base64, which is widely used when using encryption algorithms.

于 2013-03-17T18:35:32.010 に答える
0
void bytesToHex(char* dest, char* src, int size) {
    for (unsigned int i = 0; i < size; i++) {
        sprintf(&dest[i * 2], "%02x", src[i]);
    }
}

You'd have to allocate your own memory here. It would be used like this:

char myBuffer[32]
char result[65];
bytesToHex(result, myBuffer, 32);
result[64] = 0;

// print it
printf(result);

// or store it in an std::string
std::string str = string(result);
于 2013-03-17T18:52:44.873 に答える