将二进制格式的字符串转换为整数,在C语言中。

13

如何在C语言中将二进制字符串(如“010011101”)转换为整数,以及将整数(如5)转换为二进制字符串“101”?


将由1和0组成的字符串转换为二进制值。 - Jimmy
8个回答

30

标准库中的strtol函数需要一个“基数”参数,对于这个例子来说,基数应该是2。

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

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


1
在C语言中,没有内置的“null”字面量。有一个宏定义为NULL,所以需要将其大写。此外,字符串参数应该是“const”,因为函数不会修改它。 - unwind
没错。如果是我,编译器提示错误后,我可能会用“0”来解决问题 :-) - Pointy

13

如果这是一道作业题,他们可能希望你实现strtol函数,你需要编写类似以下的循环:

char* start = &binaryCharArray[0];
int total = 0;
while (*start)
{
 total *= 2;
 if (*start++ == '1') total += 1;
}
如果你想要更加高级,你可以在循环中使用这些。
   total <<= 1;
   if (*start++ == '1') total^=1;

发现了更加高级的解决方案... while (len--) {ret = (ret << 1) | (*bits++ & 1);} - Rushikesh Deshpande
1
我认为你需要从 end 开始,从右向左工作。 - jww

0
回答问题的第二部分。
char* get_binary_string(uint16_t data, unsigned char sixteen_bit)
{
    char* ret = NULL;
    if(sixteen_bit) ret = (char*)malloc(sizeof(char) * 17);
    else ret = (char*)malloc(sizeof(char) * 9);
    if(ret == NULL) return NULL;

    if(sixteen_bit){
        for(int8_t i = 15; i >= 0; i--){
            *(ret + i) = (char)((data & 1) + '0');
            data >>= 1;
        }
        *(ret + 16) = '\0';
        return ret;
    }else{
        for(int8_t i = 7; i >= 0; i--){
            *(ret + i) = (char)((data & 1) + '0');
            data >>= 1;
        }
        *(ret + 8) = '\0';
        return ret;
    }
    return ret;
}

0
回答你问题的第一部分,这里有一个我创建的简洁小巧的函数,可以将二进制字符字符串转换为整数。
 // Function used to change binary character strings to integers
int binToDec(char binCode[])
{
    while (binCode != NULL)
    {
        int base = strlen(binCode) - 1; // the base of 2 to be multiplied, we start of -1 because we dont account for the last bit here
        int sum = 0;
        for (int i = 0; i < strlen(binCode) - 1; i++) // we do not account for the last bit of the binary code here....
        {
            int decimal = 1;
            if (binCode[i] == '1')
            {
                for (int j = 0; j < base; j++) // we want to just multiply the number of true bits (not including the 1)
                {
                    decimal = decimal * 2;  
                }

                base = base - 1; // subtract base by 1 since we are moving down the string by 1
            }
            else // we encounter a zero
            {
                base = base - 1; // subtract a base multiple every time we encounter a zero...
                continue;        // carry on with the code
            }
            sum += decimal;
           // starting from the left (higher power) to the end (lowest power or 1)
        }
        for (int j = strlen(binCode) - 1; j < strlen(binCode) + 1; j++)
        { // accounting for the endian bit that is always 1
            if (binCode[j] == '1')
            {
                sum += 1; // add 1 to the sum total
            }
        }
        return sum; // return the sum as an int
    }
    return 0;
}

0
针对问题的第二部分,即“如何在C中将一个整数(比如5)转换为字符串“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;
  }
}

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;
}

0

使用方法如下:

char c[20];
int s=23;

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

输出:

10111

注意:itoa是一个非标准的C函数。 - Dave

0

我猜这真的取决于关于你的字符串/程序的一些问题。例如,如果你知道你的数字不会超过255(即你只使用8位或8个0/1),你可以创建一个函数,将其中的8位传递给它,遍历它并在每次遇到1时将其加到一个总和中,然后返回该总和。例如,如果你遇到了2^7位,就加上128,如果下一个位是2^4,就加上16。

这是我快速而简单的想法。我会在学校的时候再为你查找更多信息和谷歌一下。:D


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接