cm007
cm007

Reputation: 1392

How to print a byte as a two-digit hexadecimal character?

I need to generate random GUIDs in C, in Windows. I have:

HCRYPTPROV hCryptProv = 0;
BYTE pbBuffer[16];
int i;
if (!CryptAcquireContextW(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
    exit(1);
for (i = 0; i < N; i++) {
    if (!CryptGenRandom(hCryptProv, 16, pbBuffer))
        exit(1);
    printf("%X%X%X%X-%X%X-%X%X-%X%X-%X%X%X%X%X%X\n", pbBuffer[0], pbBuffer[1], pbBuffer[2], pbBuffer[3],
                                                     pbBuffer[4], pbBuffer[5], pbBuffer[6], pbBuffer[7],
                                                     pbBuffer[8], pbBuffer[9], pbBuffer[10], pbBuffer[11],
                                                     pbBuffer[12], pbBuffer[13], pbBuffer[14], pbBuffer[15]);
}

However, this prints any byte less than 0F as a single character (e.g., 0000-00-00-00-000000 if each pbBuffer[j] were 0). I need every single byte printed to be two characters (e.g., 00000000-0000-0000-0000-000000000000 if each pbBuffer[j] were 0). How can I do this?

Upvotes: 12

Views: 27946

Answers (1)

D.Shawley
D.Shawley

Reputation: 59563

Try printf("%02X", an_integer). The 02X says to zero-fill to two display characters.

Upvotes: 32

Related Questions