我有一个用十六进制数字填充的数组(readingreg [4])。我的目标是将数据类型转换为字符串。我已经阅读了一些建议,似乎 sprintf 是要走的路。
这是我尝试过的:
sprintf(server0, "0x%02X", readingreg[0]);
printf("This is element 0: %s\n", server0);
sprintf(server1, "0x%02X", readingreg[1]);
printf("This is element 1: %s\n", server1);
sprintf(server2, "0x%02X", readingreg[2]);
printf("This is element 2: %s\n", server2);
sprintf(server3, "0x%02X", readingreg[3]);
printf("This is element 3: %s\n", server3);
printf("This is element 0: %s\n", server0);
printf("This is element 1: %s\n", server1);
printf("This is element 2: %s\n", server2);
printf("This is element 3: %s\n", server3);
这是我的输出:
This is element 0: 0x4A
This is element 1: 0xAA
This is element 2: 0xAA
This is element 3: 0xA0
This is element 0: 0
This is element 1: A0
This is element 2: xA0
This is element 3: 0xA0
在这一点上,我对 sprintf 为我做了什么感到很困惑。我的预期输出是 server0 - server4 都保留了它们的字符串值。知道为什么会这样吗?
这是该程序的简化版本:
readingreg[0] = 4A;
readingreg[1] = AA;
readingreg[2] = AA;
readingreg[3] = A0;
char server0[1];
char server1[1];
char server2[1];
char server3[1];
完整的程序有 1000 多行代码,所以我提供的应该足以编译和运行。