Question

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.

Was it helpful?

Solution

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

OTHER TIPS

 printf ((x == 0) ? "%03x" : "0x%03x", x);
if (num == 0)
{
     printf("0");
}
else
{
     printf("%X", num);
}

Why make it hard?

if number = 0
  printf without formatting
else
  printf with formatting

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top