我想得到
int sign[8]= {0,1,0,1,0,1,1,1};
像在 strtol 函数上使用
char c = (char) strtol(sign, NULL, 2);
printf("%c\n", c);
我不知道如何在 strol 中使用符号。当我使用
c = (char) strtol("01010111", NULL, 2);
一切正常,我想得到这样的结果。
请帮忙:)
最佳答案
问题是 sign
不是字符串,它是一个小整数数组。
您可以将它们直接解释为位并将数组转换为数字,通过 strtol()
没有意义(事实上,在 C 中这样做是相当不惯用的你的方式)。
只是循环:
unsigned int array_to_int(const int *bits, size_t num_bits)
{
unsigned int ret = 0, value = 1;
for(; num_bits > 0; --num_bits, value *= 2)
ret += value * bits[num_bits - 1];
return ret;
}
关于c - Int 数组到 strtol 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862556/