2016-12-07 53 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作爲答案 –

相關問題