Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

printf

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?

like image 805
cm007 Avatar asked Dec 20 '11 20:12

cm007


People also ask

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 many hex is a byte?

So a byte -- eight binary digits -- can always be represented by two hexadecimal digits.

How do you print a byte value?

You can simply iterate the byte array and print the byte using System. out. println() method.

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


1 Answers

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

like image 136
D.Shawley Avatar answered Oct 20 '22 03:10

D.Shawley