foobarfuzzbizz
foobarfuzzbizz

Reputation: 58725

printf formatting

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

Answers (5)

Sean Bright
Sean Bright

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

paxdiablo
paxdiablo

Reputation: 882446

 printf ((x == 0) ? "%03x" : "0x%03x", x);

Upvotes: 4

user64349
user64349

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

Chris Ballance
Chris Ballance

Reputation: 34367

if (num == 0)
{
     printf("0");
}
else
{
     printf("%X", num);
}

Upvotes: 2

Joe
Joe

Reputation: 42666

Why make it hard?

if number = 0
  printf without formatting
else
  printf with formatting

Upvotes: 1

Related Questions