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).
There are 2 ways to achieve this:
using
0x%x, which ensures even0is printed as0x0.0x%Xis the only solution to print thexin lowercase and the number with uppercase hexadecimal digits. Note however that you cannot use the width prefix as the padding spaces will appear between the0xand the digits:printf(">0x%4x<", 100)will output>0x 64<using
%#x, which adds the0xprefix if the number is non zero and is compatible with the width prefix:printf(">%#6x<", 100)will output> 0x64<, but bothprintf(">%#06x<", 100)andprintf(">0x%04x<", 100)will output>0x0064<.