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.
Try: printf("%04x",a); 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified. x - Specifier for hexadecimal integer.
In C and languages based on the C syntax, the prefix 0x means hexadecimal (base 16). Thus, 0x400 = 4×(162) + 0×(161) + 0×(160) = 4×((24)2) = 22 × 28 = 210 = 1024, or one binary K.
Try:
printf("%04x",a);
0
- Left-pads the number with
zeroes (0) instead of spaces, where
padding is specified.4
(width) - Minimum number of
characters to be printed. If the
value to be printed is shorter than
this number, the result is right justified
within this width by padding on the left
with the pad character. By default this is
a blank space, but the leading zero we used
specifies a zero as the pad char.
The value is not truncated even if the result is
larger.x
- Specifier for hexadecimal
integer.More here
i use it like this:
printf("my number is 0x%02X\n",number);
// output: my number is 0x4A
Just change number "2" to any number of chars You want to print ;)
Your code has no problem. It does print the way you want. Alternatively, you can do this:
printf("%04x",a);
You can use the following snippet code:
#include<stdio.h>
int main(int argc, char *argv[]){
unsigned int i;
printf("decimal hexadecimal\n");
for (i = 0; i <= 256; i+=16)
printf("%04d 0x%04X\n", i, i);
return 0;
}
It prints both decimal and hexadecimal numbers in 4 places with zero padding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With