所以我尝试使用此方法将二进制数转换为字符串
//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/