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, eg -ea
, you'll have to handle signed values separately. Otherwise, if you want a negative value to show up as the proper unsigned conversion (ie 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.