簡體   English   中英

如何將二進制字符串轉換為無符號整數?

[英]How to convert binary string to an unsigned 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);
}

你的代碼有很多問題:

  • 如果您從索引len開始,您將訪問字符串的終止'\0'字節。
  • 您的索引不會將 go 降至 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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM