58

I have a list of numbers as below:

0, 16, 32, 48 ...

I need to output those numbers in hexadecimal as:

0000,0010,0020,0030,0040 ...

I have tried solution such as:

printf("%.4x", a); // Where a is an integer

But the result that I got was:

0000, 0001, 0002, 0003, 0004 ...

I think I'm close there. How can I fix it?

I'm not so good at printf in C.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 6
    Try `printf("%d: %.4x\n", a, a)`, I think your `a` doesn't have the value you think it has. –  Sep 06 '10 at 04:49
  • 2
    yes, you're right. i was absent minded. sorry for this foolish question... –  Sep 06 '10 at 04:58

4 Answers4

132

Try:

printf("%04x",a);
  • 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified.
  • 4 (width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

Forbin
  • 123
  • 8
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 1
    it results in: 0000, 0001, 0002, 0003, 0004 ... what I need is: 0000,0010,0020,0030,0040 ... –  Sep 06 '10 at 04:44
  • hmm, how weird ... I tried it but always show up as 0000, 0001, 0002, 0003, 0004 (I use Eclipse in Ubuntu, gcc...) –  Sep 06 '10 at 04:49
  • @tsubasa - print them out as decimal integers at the same time, just to check that the rest of your code does what you think. – detly Sep 06 '10 at 04:58
  • 2
    The original `%.4x` format notation was fine and achieves the same results as `%04x`. The issue was primarily the data supplied to the `printf()`. – Jonathan Leffler Oct 12 '13 at 14:03
9

I use it like this:

printf("my number is 0x%02X\n",number);
// Output: my number is 0x4A

Just change number "2" to any number of characters you want to print ;)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zeilja
  • 499
  • 6
  • 6
1

Your code has no problem. It does print the way you want. Alternatively, you can do this:

printf("%04x",a);
Community
  • 1
  • 1
loxxy
  • 12,990
  • 2
  • 25
  • 56
1

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

hmofrad
  • 1,784
  • 2
  • 22
  • 28