项目场景:
对于数值的打印,有时候需要打印特定的数值格式,以达到便于脚本检测和验证的目的。
问题描述:
有这么一串产品相关信息,原本以十六进制的方式打印,如 0X20390405。
现在希望打印样式为: 0X20.39.04.05。相应的代码如下:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 540607493;
printf("%x\n",a);
return 0;
}
[root@localhost tmp]# gcc main.c
[root@localhost tmp]# ./a.out
20390405
解决方案:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 540607493;
printf("%02x.%02x.%02x.%02x\n",
(a & 0xff000000) >> 24, (a & 0x00ff0000) >>16,
(a & 0x0000ff00) >> 8, (a & 0x000000ff) >> 0);
return 0;
}
[root@localhost tmp]# gcc main.c
[root@localhost tmp]# ./a.out
20.39.04.05
版权声明:本文为weixin_42109053原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。