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

标签 c

这是一个字符数组

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/

相关文章:

c - c中 'or'逻辑之间的区别

c - 二进制文件写入问题

c - float 的最大值

c - libgps 用于从 gpsd 守护程序中提取数据

棋盘问题

c - K&R 的这个例子有什么问题?

C 预处理器宏参数末尾有空格用于连接?

c - 编译良好的 C 程序中的段错误

c - 如何将整数数组分配给特定地址?

c - 在 C 中读取 csv 文件,strtok 没有返回我所期望的?