我需要在 C 中将整数转换为位字符串。我已经编写了一个函数来实现此目的(示例)并且需要知道更好的解决方案。
例如:
char* int_to_bin(int n)
{
char arr[] = "00000000000000000000000000000000"; // 32 zeros , coz int => 32 bit
int pos = 0;
while(n!=0)
{
char element = (n%2==0)?'0':'1';
arr[pos] = element;
n /= 2;
pos++;
}
char *str = malloc(sizeof(char)*(pos+1)); // need to malloc for future use
for(int i = 0; i<pos; i++) // get the reverse
{
*(str+i) = arr[pos-1-i];
}
*(str+pos) = '\0';
return str;
}
最佳答案
您可以避免内存复制并让编译器通过使用固定次数的迭代来展开循环:
char* int_to_bin(unsigned n) {
unsigned size = sizeof(n) * CHAR_BIT;
char* str = malloc(size + 1);
str[size] = 0;
while(size--) {
str[size] = '0' + (n & 1);
n >>= 1;
}
return str;
}
关于c - 在 C 中将整数转换为位串的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57498965/