Wednesday, April 6, 2011

Printf formatting

Hey all. I want to use print to print hex numbers in the form 0x###, but if the number is 0, I want to omit the 0x part. How can I do this?

Thanks!

From stackoverflow
  • Why make it hard?

    if number = 0
      printf without formatting
    else
      printf with formatting
    
  • if (num == 0)
    {
         printf("0");
    }
    else
    {
         printf("%X", num);
    }
    
    bk1e : This always omits the "0x".
  • 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
    
    Jonathan Leffler : It prints a upper-case X; the questioner requested a lower-case X. I care; I like 0xABCDEF0123 notation. But that's me being a fuss-pot. Maybe using 'x' in place of 'X' would placate the questioner.
    Jonathan Leffler : OK - fair enough. I said I was being a fuss-pot. I personally don't like the fact that to get the notation I prefer (lower case 0x, upper-case hex digits), I cannot use the standard printf() stuff; I have to write 0x%08lX or whatever; and that would not give 0 without the 0x part.
    Michael Burr : On the other hand, I find it irritating that I don't get the "0x" prefix if the value is zero, even though I'm asking for the dang prefix in general. If I wanted zero to be a special case, I'd special case it. Then again, I don't find it to be a particularly big irritation.
  • 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)

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

0 comments:

Post a Comment