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.
Asked
Active
Viewed 1.4k times
2 Answers
13
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.

Kerrek SB
- 464,522
- 92
- 875
- 1,084
-
Actually, you *can* specify a precision for the integer conversion specifiers: `printf("%.4X", x");` does so, and works as expected (for the `d`, `i`, `o`, `u`, `x` and `X` conversions, the precision specifies the minimum number of digits to appear). – caf Jul 15 '11 at 01:16
-
Yeah, but the word "precision" doesn't really apply -- you always see the exact integer. – Kerrek SB Jul 15 '11 at 01:17
-
The word "precision" is actually used in C for this though, even for integers - the `.4` part of `%.4X` is called the precision. – caf Jul 15 '11 at 01:18
-
1It would be better to use `%.4x`, i.e. use the *precision* instead of the *width*. The width includes other stuff like space for the sign, the `0x` (if `#` flag is used), etc. – R.. GitHub STOP HELPING ICE Jul 15 '11 at 01:24
-
I wonder where (in glibc's manual page) this is explained (formatting `0x618` with `%#04x` gives `0x618` (and not `0x0618`), but formatting with `%#0.4x` gives `0x0618`. The manual page says: "If a precision is given with a numeric conversion (d, i, o, u, x, and X), the 0 flag is ignored." – U. Windl Aug 28 '17 at 08:56
-
@U.Windl It's in the manpage, in the paragraphs about precision and width. The `0` of in `0x0618` for `%#0.4x` is because of the precision. If you increase the width, e.g. to `printf("%#010.4x\n", 0x618);`, it'll print ` 0x0618`, showing that the `0` flag is indeed ignored. If you remove the precision (`printf("%#010x\n", 0x618);`), it'll change to `0x00000618`. – Petr Skocik Nov 19 '17 at 18:02
-
1@PSkocik: I'd like to give you a +1, but that's not possible. Your comment was very enlightening! – U. Windl Nov 27 '17 at 08:28
6
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
-
This way of doing it results in EXACTLY the same answer as Kerrek, although uses printf flags slightly differently – J Teller Jul 15 '11 at 00:05
-