在C中将二进制格式字符串转换为int

时间:2010-02-26 16:30:57

标签: c

如何将二进制字符串(如“010011101”)转换为int,如何将int(如5)转换为C中的字符串“101”?

6 个答案:

答案 0 :(得分:20)

标准库中的strtol函数采用“base”参数,在本例中为2。

int fromBinary(const char *s) {
  return (int) strtol(s, NULL, 2);
}

(我在大约8年写的第一个C代码: - )

答案 1 :(得分:12)

如果是家庭作业问题,他们可能希望你实施strtol,你会得到这样的循环:

char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
 total *= 2;
 if (*start++ == '1') total += 1;
}

如果你想获得幻想,你可以在循环中使用它们:

   total <<= 1;
   if (*start++ == '1') total^=1;

答案 2 :(得分:0)

我想这真的取决于你的字符串/程序的一些问题。例如,如果您知道您的数字不会大于255(IE只使用8位或8 0/1),您可以创建一个函数,您可以将其从字符串中移取8位,遍历并添加每次你点击1时返回的总和。如果你点击2 ^ 7加上128,你点击的下一位是2 ^ 4加16。

这是我快速而肮脏的想法。在学校里,我想更多和谷歌一样。 :d

答案 3 :(得分:0)

对于问题的第二部分,即“如何将int(如5)转换为C中的字符串”101“,请尝试以下方法:

void
ltostr( unsigned long x, char * s, size_t n )
{
  assert( s );
  assert( n > 0 );

  memset( s, 0, n );
  int pos = n - 2;

  while( x && (pos >= 0) )
  {
    s[ pos-- ] = (x & 0x1) ? '1' : '0'; // Check LSb of x
    x >>= 1;
  }
}

答案 4 :(得分:0)

您可以使用以下编码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void)
{
   int nRC = 0;
   int nCurVal = 1;
   int sum = 0;
   char inputArray[9];
   memset(inputArray,0,9);
   scanf("%s", inputArray);
   // now walk the array:
   int nPos = strlen(inputArray)-1;
   while(nPos >= 0)
   {
      if( inputArray[nPos] == '1')
      {
         sum += nCurVal;
      }
      --nPos;
      nCurVal *= 2;
   }
   printf( "%s converted to decimal is %d\n", inputArray, sum);
   return nRC;
}

答案 5 :(得分:0)

像这样使用:

char c[20];
int s=23;

itoa(s,c,2);
puts(c);

输出:

10111
相关问题