嗨,我对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只是让我哭泣
答案 0 :(得分:4)
^
运算符不用于取幂,而是按位XOR运算符。
如果您想将数字提高到2的幂,请使用左移位运算符<<
将值1
移动到相关指数。
decimal += 1 << ((len - 1) - i);
答案 1 :(得分:2)
技巧与任何数字基数相同:对于每个输入数字,将累加器乘以数字基数并添加数字。
#include <stdio.h>
#include <string.h>
int BinaryToInt(char *binaryString)
{
int decimal = 0;
int len = strlen(binaryString);
for(int i = 0; i < len; i++) {
decimal = decimal * 2 + binaryString[i] - '0';
}
return decimal;
}
int main(void)
{
printf("%d", BinaryToInt("10000000"));
return 0;
}
节目输出:
128