這是一個家庭作業問題。我已經在網上找到了很多代碼,包括StackOverflow中的一些代碼。但我只是想要這個概念而不是代碼。我想自己實現它。所以我想實現的功能是:將單精度浮點乘以2
float_twice
- 返回位水平相當於浮點參數f
表達2*f
的。- 參數和結果都以
unsigned int
的形式傳遞,但它們被解釋爲單精度浮點值的位級表示。
我想知道如何做到這一點。我知道浮點表示。並閱讀如何繁殖兩個浮動維基頁面,但不理解它。我只是想知道它的概念/算法。
編輯:
謝謝大家。根據你的建議,我寫了下面的代碼:
unsigned float_twice(unsigned uf) {
int s = (uf >> 31) << 31;
int e = ((uf >> 23) & 0xFF) << 23;
int f = uf & 0x7FFF;
// if exponent is all 1's then its a special value NaN/infinity
if (e == 0xFF000000){
return uf;
} else if (e > 0){ //if exponent is bigger than zero(not all zeros', not al 1's,
// then its in normal form, add a number to the exponent
return uf + (1 << 23);
} else { // if not exponent not all 1's and not bigger than zero, then its all
// 0's, meaning denormalized form, and we have to add one to fraction
return uf +1;
} //end of if
} //end of function
float的一個組件表示二的冪。這是你應該感興趣的部分。 – user2357112 2014-09-19 16:14:23
如果你知道表示的工作原理,試試'f'的例子,並將其編碼與'2 * f'的編碼進行比較。任意浮點數的乘法比乘以2要複雜得多,所以如果你現在有麻煩的理解前者可能無關緊要。 – mafso 2014-09-19 16:17:02
一個好的開始可能是'printf()'輸出'f'和'2 * f'的位模式。 – 5gon12eder 2014-09-19 16:17:13