我正在尝试将二进制字符串转换为无符号整数,但我仍然无法找到实现它的方法,这是我的代码,可能没有多大意义:
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'
字节。 - 您的索引不会下降到 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;
}
关于c - 如何将二进制字符串转换为无符号整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747110/