16位浮点 c语言,C语言中的16位浮点乘法
我正在開發(fā)一個小項目,我需要浮點乘法和16位浮點數(shù)(半精度)。不幸的是,我遇到了算法的一些問題:
示例輸出
1 * 5 = 5
2 * 5 = 10
3 * 5 = 14.5
4 * 5 = 20
5 * 5 = 24.5
100 * 4 = 100
100 * 5 = 482
源代碼
const int bits = 16;
const int exponent_length = 5;
const int fraction_length = 10;
const int bias = pow(2, exponent_length - 1) - 1;
const int exponent_mask = ((1 << 5) - 1) << fraction_length;
const int fraction_mask = (1 << fraction_length) - 1;
const int hidden_bit = (1 << 10); // Was 1 << 11 before update 1
int float_mul(int f1, int f2) {
int res_exp = 0;
int res_frac = 0;
int result = 0;
int exp1 = (f1 & exponent_mask) >> fraction_length;
int exp2 = (f2 & exponent_mask) >> fraction_length;
int frac1 = (f1 & fraction_mask) | hidden_bit;
int frac2 = (f2 & fraction_mask) | hidden_bit;
// Add exponents
res_exp = exp1 + exp2 - bias; // Remove double bias
// Multiply significants
res_frac = frac1 * frac2; // 11 bit * 11 bit → 22 bit!
// Shift 22bit int right to fit into 10 bit
if (highest_bit_pos(res_mant) == 21) {
res_mant >>= 11;
res_exp += 1;
} else {
res_mant >>= 10;
}
res_frac &= ~hidden_bit; // Remove hidden bit
// Construct float
return (res_exp << bits - exponent_length - 1) | res_frac;
}
順便說一下:我將浮點數(shù)存儲在整數(shù)中,因為我會嘗試將此代碼移植到某種沒有浮點操作的匯編程序。
問題
為什么代碼僅適用于某些值?我忘記了一些規(guī)范化或類似的嗎?或者它只是偶然起作用?
免責聲明:我不是CompSci學生,它是一個休閑項目;)
更新#1
感謝Eric Postpischil的評論,我注意到代碼存在一個問題:hidden_bit標志被一個人關閉(應該是1 << 10)。有了這個改變,我不再獲得小數(shù)位數(shù),但仍有一些計算結果(例如3?3=20)。我假設,它是res_frac轉變,如答案中所描述的那樣。
更新#2
代碼的第二個問題確實是res_frac轉移。在更新#1之后,當?shù)玫絝rac1 * frac2的22位結果時,我得到了錯誤的結果。我已使用更正的班次語句更新了上面的代碼。感謝所有的評論和回答! :)
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎總結
以上是生活随笔為你收集整理的16位浮点 c语言,C语言中的16位浮点乘法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 土木工程和计算机专硕,第一次发帖 关于
- 下一篇: python树莓派串口通信实例_树莓派通