I'm creating a program that prints a signed 64-bit variable in hexadecimal and octal format. I searched online for the format specifier, but I only found results for unsigned 64-bit integers.
I'm creating a program that prints a signed 64-bit variable in hexadecimal and octal format. I searched online for the format specifier, but I only found results for unsigned 64-bit integers.
Specifiers %o and %x indeed are defined for unsigned integral values only. In case of a signed input, and if you want to show a signed value like -234 with a "sign" in hex as well, e.g. -ea, you'll have to handle signed values separately.
Otherwise, if you want a negative value to show up as the proper unsigned conversion (i.e. the two's complement representation), simply cast it to unsigned:
int main() {
int input = -234;
if (input < 0) {
printf("-%x\n", (unsigned)(-input));
} else {
printf("%x\n", (unsigned)input);
}
printf("%x\n", (unsigned)input);
}
Output:
-ea
ffffff16