0
我只是從C開始,但我現在正在做的是一個簡單的數學運算。我想要的是?我想獲得指數並返回功率二的函數。我想用邏輯移位運算符。 Wiki: Logical shifts如何在C中實現邏輯移位的兩個冪?
邏輯移位可以是如由二的冪執行 乘法或除法的無符號整數的有效的方法是有用的。 在有符號或無符號二進制數字上左移n位具有將其乘以2n的效果 。
但有一件事我不明白,它不適用於大的指數,例如32.詳情見下面的代碼。那麼,如何在不使用數學庫的情況下實現這樣的功能呢?提前致謝。
long power_of_two_ext(int exp) {
exp = 32; // for testing purpose only
long retL = pow(2, exp);
printf("MATH pow() and long ---> %ld\n", retL);
long retL2 = 1 << exp;
printf("Shift bits left and long ---> %ld\n", retL2);
long long retL3 = 1 << exp;
printf("Left shift and long ---> %llu\n", retL3);
return retL;
}
MATH pow() and long ---> 4294967296
Left shift and long long ---> 1
Left shift and long ---> 1
左移位有其限制,因爲你已經找到了。 – ryantxr