Home > Net >  How to print a four character hexadecimal in C?
How to print a four character hexadecimal in C?

Time:03-04

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

  1. Limit value to the [0...0xFFFF] range.

  2. 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);
  •  Tags:  
  • c
  • Related