Search code examples
chexprintfformat-specifiers

How to print hexadecimal values in "0x" format in C


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


Solution

  • 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<.