1

I am trying to print hexadecimal values in C.

A simple known program to print hexadecimal value...( Using %x or %X format specifier)

#include<stdio.h>

int main()
{
    unsigned int num = 10;
    printf("hexadecimal value of %u is %x\n", num, num);
}

Output: hexadecimal value of 10 is a

Instead of getting output as a, I need to get output as 0xa in hexadecimal format (making if more explicit for the user that the value in expresses in hexadecimal format).

8
  • 1
    %#x also works: see en.cppreference.com/w/c/io/fprintf
    – paddy
    Commented Aug 8, 2023 at 5:18
  • I don't want to use ox before %x. %x in gcc (11.4.0) compiler it doesn't expects unsigned int. it works fine.
    – ASWIN
    Commented Aug 8, 2023 at 5:19
  • @TomKarzes Could please share me the link where i can see the documentation correctly...
    – ASWIN
    Commented Aug 8, 2023 at 5:35
  • @ASWIN Look at the man page for printf(3) Scroll down to where o, u, x, X are documented. It says The unsigned int argument is converted to unsigned octal (o), unsigned decimal (u), or unsigned hexadecimal (x and X) notation. The # modifier is documented above that, under "flag characters".
    – Tom Karzes
    Commented Aug 8, 2023 at 5:39
  • 1
    @ASWIN No, because %d expects a signed int. You could use %u instead of %d, which prints an unsigned decimal value. So you could do unsigned int num = 10; then printf("%u %#x\n", num, num); That would be strictly correct, since both format specifiers expect an unsigned int.
    – Tom Karzes
    Commented Aug 8, 2023 at 6:19

2 Answers 2

2

There are 2 ways to achieve this:

  • using 0x%x, which ensures even 0 is printed as 0x0. 0x%X is the only solution to print the x in lowercase and the number with uppercase hexadecimal digits. Note however that you cannot use the width prefix as the padding spaces will appear between the 0x and the digits: printf(">0x%4x<", 100) will output >0x 64<

  • using %#x, which adds the 0x prefix if the number is non zero and is compatible with the width prefix: printf(">%#6x<", 100) will output > 0x64<, but both printf(">%#06x<", 100) and printf(">0x%04x<", 100) will output >0x0064<.

0
2

The other answers have explained well how the "0x" prefix can be obtained.

I would like to add that hexadecimal numbers are often used with a fixed width (e.g. 2 or 4 digits). This can be obtained as follows:

  printf("0x%04x", num);

which will print e.g.

  0x0054

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.