gpt4 book ai didi

c - 将 char 数组转换为十六进制字符串并将其打印在一行中的方法

转载 作者:行者123 更新时间:2023-11-30 17:23:03 25 4
gpt4 key购买 nike

这是一个字符数组

char temp[] ={0x1f,0x2d,0x3c};

我想使用 __android_log_print 打印温度,如何将其转换为“1f2d3c”并在一行中打印而不需要 for 循环?

What i expected

enter image description here

Reality

enter image description here

最佳答案

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com