Kian
Kian

Reputation: 33

printf precision

I am writing a program in C and I have several printf statements for debugging. Is there a way to change the precision for a HEX output on printf? Example. I have 0xFFF but I want it to print out 0x0FFF.

Upvotes: 3

Views: 14218

Answers (2)

J Teller
J Teller

Reputation: 1431

You can use the precision field for printf when printing in hex.

For instance:

int i = 0xff;
printf ("i is 0x%.4X\n", i);
printf ("i is  %#.4X\n", i);

Will both print: 0x00FF

Upvotes: 6

Kerrek SB
Kerrek SB

Reputation: 477040

Say printf("%04X", x);.

The 0 means "pad with zeros", the 4 means "at least four characters wide".

For integers, one doesn't use the term "precision" (because integers are precise), but rather "field width" or something like that. Precision is the number of digits in scientific notation when printing floats.

Upvotes: 13

Related Questions