What exactly does '%02x' do?

Asked

Viewed 560 times

3

I was seeing some examples function hash of Openssl and I came across the format specifier %02x. I do not know very well its purpose we codes that I saw. I even understand that the %02x serves to fill the field with zeros and 2 is the number of zeros that will have in this fill (I think this).

Well, here’s some code I made up where I had to use (I don’t know why I had to use) the %02x:

#include <stdio.h>
#include <string.h>
#include <string.h>
#include <openssl/sha.h>

void get_string(char *string, size_t max_input_size){

    fgets(string, max_input_size, stdin);

    unsigned int len=strlen(string);

    string[len-1]='\0';
}

int main(void){

    char string[50];
    unsigned char digest[SHA256_DIGEST_LENGTH];

    printf("Write >");
    get_string(string, 50);

    SHA256((unsigned char*)string, strlen(string), digest);

    char stringMD[SHA256_DIGEST_LENGTH*2+1];

    for(unsigned int i=0; i<SHA256_DIGEST_LENGTH; i++){

        sprintf(&stringMD[i*2], "%02x", (unsigned int)digest[i]);
    }

    printf("\n\nDigest: %s\n\n", stringMD);

    return 0;
}

Enforcement (with the %02x):

Write >FN P90

Digest: 45603ce52cd32a33e3e60c219d0c18e6bd32af24ac39aa000d84e763d23c3031

Execution (with only the %x):

Write >FN P90

Digest: 45603ce52cd32a33e3e6c

However, what is the purpose of %02x?

2 answers

3


According to the documentation displays the integer as hexadecimal ensuring it always has 2 digits, with 0 used on the left if it has only 1 or 0 digits. It is usually the only way to generate hexadecimal correctly, especially in cases where it is only part of a larger number.

0

You have a "string" called stringMD, that may have garbage at the beginning of the program.

If you don’t fill all their positions with something, in a certain region of it there may be characters \0.

How you’re filling it in two by two (see below),

sprintf(/* destaque ao i*2 >>>>*/ &stringMD[i*2], "%02x", ...

if you forget the 02 of the format, the completion may be partial.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.