简体   繁体   English

使用 sprintf 转换和打印十六进制值(保留前导零)

[英]Converting and printing hex values using sprintf(keeping the leading zeroes)

I have the following C code which takes two long integer values and convert them to two hex strings using the sprintf function:我有以下 C 代码,它采用两个长整数值并使用 sprintf 函数将它们转换为两个十六进制字符串:

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

Use

sprintf(reversed_src, "%04x", ( 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.请注意,对于2 * sizeof( long )类型的对象,如果表达式2 * sizeof( long ) (十六进制数字的数量)可以等于 8 或 16。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM