views:

117

answers:

2

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 is:

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

I think I'm close there. Can anybody help as I'm not so good at printf in C.

Thanks.

+4  A: 

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 padded with blank spaces. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

codaddict
it results in: 0000, 0001, 0002, 0003, 0004 ... what I need is: 0000,0010,0020,0030,0040 ...
tsubasa
It works for me. http://www.ideone.com/2VzY1
codaddict
hmm, how weird ... I tried it but always show up as 0000, 0001, 0002, 0003, 0004 (I use Eclipse in Ubuntu, gcc...)
tsubasa
i found my problem. its a different issue. thank you much.
tsubasa
@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
A: 

ur code has no problem. It does print the way you want....alternatively u can do this:

printf("%04x",a);
loxxy