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?
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 .
So a byte -- eight binary digits -- can always be represented by two hexadecimal digits.
You can simply iterate the byte array and print the byte using System. out. println() method.
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).
Try printf("%02X", an_integer)
. The 02X
says to zero-fill to two display characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With