Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print signed hexadecimal in C

Tags:

c

hex

I know we can use printf("%04X", value); to print unsigned hexadecimal values.

Is there a similar flag or a function in C that you can use to print signed hex values?

Something similar like this

Binary   Hex (signed) Hex (unsigned)
-------- ----------- --------------

00000010 +0x2        0x2
00000001 +0x1        0x1
00000000 +0x0        0x0
11111111 -0x1        0xFF
11111110 -0x2        0xFE
11111101 -0x3        0xFD
like image 806
David Avatar asked Mar 07 '12 14:03

David


People also ask

How do you represent a hexadecimal number in C?

In C programming language, hexadecimal value is represented as 0x or 0X and to input hexadecimal value using scanf which has format specifiers like %x or %X.

Are hexadecimal signed or unsigned?

A hexadecimal value is int as long as the value fits into int and for larger values it is unsigned , then long , then unsigned long etc. See Section 6.4.

Which formatting character is used to for hexadecimal?

The AHEX format is used to read the hexadecimal representation of standard characters. Each set of two hexadecimal characters represents one standard character. The w specification refers to columns of the hexadecimal representation and must be an even number.


2 Answers

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.

like image 196
R.. GitHub STOP HELPING ICE Avatar answered Sep 16 '22 21:09

R.. GitHub STOP HELPING ICE


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 ;-)

like image 29
Michael Krelin - hacker Avatar answered Sep 19 '22 21:09

Michael Krelin - hacker