如何将二进制字符串转换为无符号整数?

问题描述 投票:0回答:2

我正在尝试将二进制字符串转换为无符号的int,但仍然无法实现,这是我的代码,可能没有多大意义:

unsigned int binary_to_uint(const char *b)
{
    unsigned int k = 2;
    unsigned int i;
    unsigned int c;
    unsigned int len;
    if (b == NULL)
        return (0);
    len = strlen(b);
    for (c = len; c > 0; c--)
    {
        if (b[c] != 48 || b[c] != 49)
            return (0);
        if (b[c] == '1')
        {
            i += atoi(b) * k;
        }
        k *= 2;
    }
    return (i);
}
c
2个回答
-1
投票

if(b [c]!= 48 || b [c]!= 49)中的条件始终为真,并且在C范围内,索引的范围是0到len-1

unsigned int binary_to_uint( const char *b)
{
 unsigned int k = 1;
 unsigned int i=0;
 int c;
 unsigned int len;

 len = strlen(b);

  for (c = len-1; c >= 0; c--)
 {
  if (b[c] != '0' && b[c] != '1')
      return (0);
    if (b[c] == '1')
    {
     i += k;
     }
    k *= 2;
}
 return (i);
}

3
投票

您的代码中有很多问题:

  • 如果从索引len开始,则访问字符串的终止'\0'字节。
  • 您的索引不会降到0,这意味着您错过了第一位数字。
  • 在循环过程中,您始终使用atoi(b),这不是很有用。
  • 您从最右边的数字开始,但使用k=2作为其值,而不是1。

通常按照简单的方案进行这种转换:

unsigned int binary_to_uint(const char *b)
{
  unsigned int val = 0;
  int i = 0;

  if (b == NULL)
    return 0;

  while (b[i] == '0' || b[i] == '1')
  {  // Found another digit.
    val <<= 1;
    val += b[i]-'0';
    i++;
  }
  return val;
}
© www.soinside.com 2019 - 2024. All rights reserved.