2016-12-07 9 views
0

こんにちは私はかなり新しいですが、私はプログラムのためにバイナリ文字列を10進数に変換する必要があります。ここに私の現在のコードです:ここ奇妙な結果を与えるcのバイナリから10進アルゴリズム

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 

私はこれが動作しない理由として困惑している、すべてのヘルプは大歓迎です。前もって感謝します!

シモンズ:私はそうCはちょうど私が^オペレータは、べき乗のためではなく、ビット単位のXOR演算子です

答えて

4

を叫ぶなり、現時点でのJavaに慣れています。

数値を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; 
} 

プログラム出力:Javaへ

128 
+0

+ binaryString [i]の仕組みがわかりません。 cは自動的にそれを整数に変換しますか? –

+0

'char'型は、計算の前に' int'に昇格します。 '' 0 ''は、ASCIIまたはEBCDICまたは他の文字コード調整として減算されます。数値エンコーディングは連続している必要があります。それは 'decimal * 2 +(binaryString [i] - '0')' –

+0

として書かれた方がより明確になりました。どのようなコンパイラと標準を使っていますか? gcc c99でこれを実行すると、私は答えとして64を返します –