reality displays
reality displays

Reputation: 751

why does following printf print 0x32

#include<stdio.h>
int main ()
{
printf("%#04x",50);
}

Some one showed me above code and I could not understand it since I do have used printf in C programs but above sort of use I saw in my life for the first time. Why did above code prints output as

0x32

Can some one give me a link or reference to some thing so that I can understand it better.

Upvotes: 1

Views: 1399

Answers (3)

Victor Zamanian
Victor Zamanian

Reputation: 3180

From the printf(3) manual page:

The flag characters

The character % is followed by zero or more of the following flags:

# — The value should be converted to an "alternate form". For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already). For x and X conversions, a nonzero result has the string "0x" (or "0X" for X conversions) prepended to it. For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows). For g and G conversions, trailing zeros are not removed from the result as they would otherwise be. For other conversions, the result is undefined.

Other flags omitted...

Thus, %# prepends "0x" to the output since the output format is x. The 0 is there to use 0 (zeros) for padding. Then the number 4 says the total number of characters to print is four. Had the number 4 been exchanged with 10, the output would have been 0x00000032 – a total of 10 characters.

Upvotes: 5

Simone
Simone

Reputation: 11797

Because %x formats the given value into hexadecimal.

In facts, 0x32 (hex) == 50 (decimal).

This is a good primer for reference.

Upvotes: 2

Martin B
Martin B

Reputation: 24140

50 decimal is 32 hexadecimal.

Apart from that, the documentation should tell you all you need to know.

Upvotes: 5

Related Questions