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

时间:2014-05-07 03:38:36

标签: 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)。

非常感谢任何帮助。

5 个答案:

答案 0 :(得分:1)

首先,将temp声明为:

char temp[2];

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

使用sprintf()函数:

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

然后:

strcat(str, temp);

答案 1 :(得分:0)

我会尝试这样的事情:

int idx(char cc)
{
  if (cc >= '0' && cc <= '9')
    return cc - '0' ;
  else if (cc >= 'A' && cc < 'F')
    return cc - 'A' + 10 ;
  else
    return cc - 'a' + 10 ;
}

void ConvertToBinary (int value, char *output)
{
   char *digits [] = { "0000", "0001", "0010", "0011", 
                       "0100", "0101", "0110", "0111",
                       "1000", "1001", "1010", "1011",
                       "1100", "1101", "1110", "1111", } ;

   char buffer [32] ;
   output [0] = 0 ;

   sprintf (buffer, "%x", value) ;

   int ii ;
   for (ii = 0 ; buffer [ii] != 0 ; ++ ii)
   {

      strcat (output, digits [idx (buffer [ii])]) ;
   }       

   return ;
}

我还指出你的str缓冲区太小了。

答案 2 :(得分:0)

问题代码非常接近。

以下代码有效:

int nGiven = 0x1234;    //n is a input number   
int nTemp;
int nBitCounter=0;
char str[18];
char temp[2];

strcpy(str, "0");

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

/* store the binary number into a string */
for(; nBitCounter; nBitCounter--)
   {
   int binNum;

   nTemp = 1 << (nBitCounter - 1);
   binNum = (nTemp & nGiven) >> (nBitCounter - 1);
// _itoa(binNum, temp, 10);

我无法访问名为&#39; _itoa()&#39;的功能。所以请改用snprintf()。

   snprintf(temp, sizeof(temp), "%d", binNum);
   strcat(str, temp);
   }

printf("%s\n", str);

答案 3 :(得分:0)

您的代码比它需要的更复杂。假设您想要删除前导零,因为您的代码似乎表明:

#include <limits.h>
#include <stdio.h>

int main()
{
    unsigned int nTemp = 123456789;
    char buf[CHAR_BIT * sizeof(int) + 1];
    char *ptr = buf;

    for ( int i = CHAR_BIT * sizeof(int); i--; )
    {
       if ( nTemp & (1u << i) )
           *ptr++ = '1';
       else if ( ptr != buf )
           *ptr++ = '0';
    }
    *ptr = 0;

    printf("%s\n", buf);
}

这将为0的输入提供一个空白字符串,您可以通过在结尾处对if (ptr == buf)进行标记并采取措施来更改该字符串。

答案 4 :(得分:-2)

char * temp;

.....

temp = malloc(nBitCounter + 1);
temp[nBitCounter] = '\0';

for (; nBitCounter > 0; nBitCounter--) {
//  get the binNum by nBitCounter;
    temp[nBitCounter - 1] = binNum + '0';  // if 0, you get '0'; if 1, you get '1'
}

strcat(str, temp);
free(temp);
相关问题