susenj
susenj

Reputation: 428

%02x format specifier for char array

I have read about %02x format specifiers but when it comes to an argument of type char array, I am unable to understand the output of the following piece of code:

int main() {
    // your code goes here
    char str[6] = "abcde";
    char t[3];

    snprintf(t,3,"%02x",str);
    printf("\t%s",t);
    return 0;
}

Output:

bf

How str is being parsed under this format specifier, is a point of concern. What I feel, the output should have been "ab" (without quotes).

Upvotes: 1

Views: 17009

Answers (3)

mckenzm
mckenzm

Reputation: 1820

The point to make here is that if you are printing anything using %02x then you should be using it for each byte. It is common when printing a hash digest to declare a field of size twice the digest size (+1 for \0 if a string) and then populate it with repetitive sprintf() calls.

So one needs to loop through the bytes.

Upvotes: 2

harper
harper

Reputation: 13690

You should read your source carefully. They might use something like this:

int main() {
    char str[6] = "abcde";
    char t[2*6] = { 0 };
    int i;

    for (i = 0; i <= 5; ++i)
    {
        snprintf(t+2*i, sizeof(t)-2*(i), "%02x", str[i]);
    }
    printf("\t%s",t);
    return 0;
}

The %02x is used to convert one character to a hexadecimal string. Therefore you need to access individual charaters of str. You can build a line as my code shows or you can output each converted string as your fragment shows. But then it doesn't make sense to use the temporary variable t.

Edit: Fixed code.

Upvotes: 0

Kaslai
Kaslai

Reputation: 2505

Have a look at the CPlusPlus entry on printf. I think the format specifier you are looking for is %2.2s, which limits the minimum and maximum number of characters printed to 2, and it will print a string, rather than the value of your pointer.

main(){
    printf("%2.2s","abcde");
    return 0;
}

This will print "ab" (without the quotes). The same format rules apply to the entire printf family, including snprintf.

%02x is a format specifier that tells the parser that your value is a number, you want it to be printed in base 16, you want there to be at least 2 characters printed, and that any padding it applies should be full of zeroes, rather than spaces. You need to use some version of %s for printing strings.

Upvotes: 1

Related Questions