c - 需要帮助将二进制数转换为 C 中的字符串

标签 c string

所以我尝试使用此方法将二进制数转换为字符串

//convert input to binary
nTemp = nGiven; //n is a input number
int nTemp;
int nBitCounter = 0;
char str[18];
 char temp[1];

strcpy(str, "0");

 /* count the number of bits of the given number */
for (; nTemp != 0; nBitCounter++)
    nTemp = nTemp >> 1;

/* store the binary number into a string */
for (; nBitCounter>0; nBitCounter--) {
    nTemp = 1 << (nBitCounter - 1);
    int binNum = (nTemp & nGiven) >> (nBitCounter - 1);
    printf("%d", binNum);
    _itoa(binNum, temp, 10);
    strcat(str, temp);
}

但我不知道如何正确地做我想做的事。 binNum 的打印是正确的,但我不知道如何将此二进制表示形式存储为字符串。在第二个“for”循环中,我需要将 binNum 存储为字符(temp),然后将其附加到字符串(str)。

任何帮助将不胜感激。

最佳答案

首先,将 temp 声明为:

char temp[2];

因为您需要具有空字符的字节。

使用 sprintf() 函数:

sprintf(temp,"%d", binNum);

然后:

strcat(str, temp);

关于c - 需要帮助将二进制数转换为 C 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508285/

相关文章:

c - 如何增加指针地址和指针的值?

java - 在 Java 中执行 Java 代码

string - 绳索数据结构权重是节点中的字符加上左子树或左右子树的权重?

创建一个大整型

c - 高效的文件系统搜索

C - 如何修改函数内部的指针数组

string - 如何根据标记将字符串分解为数组?

string - 生成特定格式的唯一字符串的算法

Python:在字符串中查找模式

c - 可移植地防止函数内联