首页 > 解决方案 > 将 Int 数组转换为 Ascii 字符串

问题描述

我有一个 Int 数组,例如:

int testarray[20];

testarray[0] = 0x5A;
...
testarray[19] = 0x57;

并希望将其转换为 Ascii 字符串 (char*)。我怎样才能做到这一点?

标签: c

解决方案


只需将值复制intchar数组中,不要忘记字符串终止符。

像这样的东西:

#include <stddef.h>
#include <stdlib.h>

#define ARR_SIZE 3

char *to_str(const int testarray[ARR_SIZE])
{
    char *str = malloc(ARR_SIZE + 1);
    if (!str) {
        return NULL;
    }

    for (int i = 0; i < ARR_SIZE; ++i)
        str[i] = testarray[i];
    str[ARR_SIZE] = '\0';

    return str;
}

推荐阅读