Home > Mobile >  Converting and printing hex values using sprintf(keeping the leading zeroes)
Converting and printing hex values using sprintf(keeping the leading zeroes)

Time:10-13

I have the following C code which takes two long integer values and convert them to two hex strings using the sprintf function:

void reverse_and_encode(FILE *fpt, long *src, long *dst) {
    char reversed_src[5], reversed_dst[5];
    sprintf(reversed_src, "%x", *dst);
    sprintf(reversed_dst, "%x", *src);
    printf("Reversed Source: %s\n", reversed_src);
    printf("Reversed Destination: %s\n", reversed_dst);
}

But when I print the hex value strings, I can't get the leading zero in the output. Eg.

Reversed Source: f168 // for integer 61800
Reversed Destination: 1bb // This output should be "01bb" for integer 443

CodePudding user response:

Use

sprintf(reversed_src, "x", ( unsigned int )*dst);

Pay attention to that in general if the the expression 2 * sizeof( long ) (the number of hex digits) can be equal to 8 or 16.for an object of the type long. So you need to declare the arrays like

char reversed_src[2 * sizeof( long )   1], reversed_dst[2 * sizeof( long )   2];

and then write for example

sprintf(reversed_src, "%0*lx", 
        ( int )( 2 * sizeof( long ) ), ( unsigned long )*dst);

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    enum { N  = 2 * sizeof( long ) };
    char reversed_src [N   1];

    long x = 0xABCDEF;

    sprintf( reversed_src, "%0*lX", N, ( unsigned long )x );

    puts( reversed_src );
   
    return 0;
}

The program output is

0000000000ABCDEF
  • Related