嗨,我相當新的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此刻Ç只是讓我哭
*捂臉*太習慣於去渣,感謝您的幫助! –