将Int数组转换为Ascii字符串

时间:2020-04-21 15:54:33

标签: c

我有一个整数数组,例如:

int testarray [20];

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

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

1 个答案:

答案 0 :(得分:0)

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

类似这样的东西:

#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;
}