2016-12-07 52 views
0

嗨,我相当新的c,但我正在写一个程序,我需要将二进制字符串转换为十进制数字。这里是我当前的代码: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此刻Ç只是让我哭

回答

4

^操作不是幂,而是改为按位异或运算符。

如果要将数字提高到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 
+0

我不知道+ binaryString [i]是如何工作的。 c是否会自动将其转换为整数? –

+0

在计算之前,'char'类型被提升为'int'。将'0'减去ASCII或EBCDIC或其他字符编码调整。数字编码需要连续。如果写成'decimal * 2 +(binaryString [i] - '0'),那可能会更清晰一些。 –

+0

您使用什么编译器和标准?导致与gcc c99运行这给我64作为答案 –

相关问题