这是一个字符数组
char temp[] ={0x1f,0x2d,0x3c};
我想使用 __android_log_print 打印温度,如何将其转换为“1f2d3c”并在一行中打印而不需要 for 循环?
What i expected
Reality
最佳答案
将 printHex
函数中的 printf
替换为日志函数。只要数组以 0 结尾并且中间没有 0 字节,您就可以不传递数组的长度,因此您可以使用 strlen
来查找长度。
#include <stdio.h>
#include <string.h>
void printHex(char* digits, int len)
{
int i;
char* str;
str = malloc(len * 2 + 1);
memset(str, 0, len * 2 + 1);
for(i = 0; i < len; ++i)
{
char temp[3];
sprintf(temp, "%02x", digits[i]);
strcat(str, temp);
}
printf("%s\n", str);
free(str);
}
int main(void)
{
char temp[] ={0x1f,0x2d,0x3c,4,0,5,0,6,7,8};
printHex(temp, sizeof(temp));
return 0;
}
关于c - 将 char 数组转换为十六进制字符串并将其打印在一行中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772642/