Reputation: 58725
I want to use printf
to display hex numbers in the form 0x###
, but if the number is 0, I want to omit the 0x
part.
Upvotes: 0
Views: 2218
Reputation: 120704
printf("%#x", number);
Note that this does exactly what you want. If the value of number is 0, it prints 0, otherwise it prints in hex. Example:
int x = 0;
int y = 548548;
printf("%#x %#x\n", x, y);
Results in:
0 0x85ec4
Upvotes: 16
Reputation: 613
Couldn't you just use an if statement to check if the number is 0 then figure out if you should print it as a 0x### or just 000 (or 0 if that was what you were looking for)
Upvotes: 0
Reputation: 34367
if (num == 0)
{
printf("0");
}
else
{
printf("%X", num);
}
Upvotes: 2
Reputation: 42666
Why make it hard?
if number = 0 printf without formatting else printf with formatting
Upvotes: 1