for (int x= 7; 0<=x; x--) {
size_t x_val = ((1<<4)-1) & io>>x*4;
printf("%lX", x_val);
Trying to print a hexadecimal number here after converting it from integer. While the conversion is successful, the output is FFFFFFCD
instead of the desired output FFCD
. How can I limit maximum 4 characters to be printed?
CodePudding user response:
to print a four character hexadecimal
Limit value to the [0...0xFFFF] range.
Print 4 digits padded with zeros with the correct specifier.
Example
unsigned masked_value = io & 0xFFFF;
printf("X\n", masked_value);
CodePudding user response:
Try this one,
You can use hh
to tell printf that the argument is an unsigned char
. Use 0
to get zero padding and 4
to set the width to 4
. x
or X
for lower/uppercase hex
characters.
uint8_t a = 0x0a;
printf("hhX", a); // Prints "0A"
printf("0xhhx", a);