How to print signed hexadecimal in C How to print signed hexadecimal in C c c

How to print signed hexadecimal in C


Unfortunately C's printf function has no way to do this directly. You could of course instead try:

printf("%s%x\n", x<0 ? "-" : "", x<0 ? -(unsigned)x : x);

This should also work for handling INT_MIN.


No, but you can do something like

printf("%c%04X", (x<0) ? '-' : ' ', (x<0) ?-x : x);

But, as other point out, it is doubtful whether there is a valid reason to do so. According to your post, you do understand what you're asking for, so it's all your fault ;-)


Here is a simpler version:

#include <stdio.h>#include <stdib.h>...printf("%c%#x\n", "+-"[x < 0], (unsigned)abs(x));