c - 在 C 中将整数转换为位串的最佳方法是什么

标签 c algorithm

我需要在 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/

相关文章:

c - 如何搜索有gid的群组?

c - 将 double 型数组添加到未定义长度数组的结构中

c - 结构指针数组的问题

c++ - 没有重复的中点圆?

无法从哈希表中检索所有数据

我可以为C中的多个变量分配相同的值吗?

c - gwan是如何实现异步 Action 的?

c# - 如何在不读取文件的情况下获取行数

java - 内存斐波那契码的空间复杂度

algorithm - 我试图找到一个 "bartender algorithm"