cprintfformat-specifiers

Why would an int be formatted as %#X in a printf function?


I'm debugging some code (not written by myself) and have an int index being printed with %#X in a printf function. From my understanding %#X is an uppercase unsigned hexadecimal integer.

Is this ok/is there any way around this?


Solution

  • The # conversion specifier indicates that the alternative conversion should be used.

    From cppreference:

    In the alternative implementation 0x or 0X is prefixed to results if the converted value is nonzero.

    So, it would seem this is intentional by the author.

    If you are asking instead about the unsigned part of this, %X is always unsigned. If you have a signed value and you want your hex value to be prefixed with a negative sign for negatives, you will have to roll your own.

    Otherwise, it's quite fine to have a signed value as input -- it will simply be reinterpreted as unsigned. Unless this is the bug you've identified in your program! ;)