gpt4 book ai didi

c - c中的二进制到十进制算法给出奇怪的结果

转载 作者:太空宇宙 更新时间:2023-11-04 05:35:08 25 4
gpt4 key购买 nike

您好,我是 c 语言的新手,但对于我正在编写的程序,我需要将二进制字符串转换为十进制数。这是我当前的代码:

int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++)
{

if(binaryString[i] == '1')
decimal += 2^((len - 1) - i);
printf("i is %i and dec is %i and the char is %c but the length is %i\n", i, decimal, binaryString[i], len);
}
return decimal;
}

int main(int argc, char **argv)
{
printf("%i", BinaryToInt("10000000"));
}

这是输出:

i is 0 and dec is 5 and the char is 1 but the length is 8
i is 1 and dec is 5 and the char is 0 but the length is 8
i is 2 and dec is 5 and the char is 0 but the length is 8
i is 3 and dec is 5 and the char is 0 but the length is 8
i is 4 and dec is 5 and the char is 0 but the length is 8
i is 5 and dec is 5 and the char is 0 but the length is 8
i is 6 and dec is 5 and the char is 0 but the length is 8
i is 7 and dec is 5 and the char is 0 but the length is 8
5

我很困惑为什么这不起作用,非常感谢所有帮助。提前致谢!

Ps:我习惯了java,所以现在C让我哭了

最佳答案

^运算符不是用于求幂,而是按位异或运算符。

如果你想增加一个数的 2 次方,使用左移运算符 <<移动值 1由相关指数。

decimal += 1 << ((len - 1) - i);

关于c - c中的二进制到十进制算法给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com