所以我正在尝试使用这种方法将二进制数转换为字符串
//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存储为一个字符(临时),然后将其附加到字符串(str)中。
任何帮助将不胜感激。
首先,将temp声明为:
char temp[2];
因为您需要一个具有空字符的字节。
使用sprintf()函数:
sprintf(temp,"%d", binNum);
接着:
strcat(str, temp);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句