Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- unsigned add_floats(unsigned f1, unsigned f2) {
- unsigned m_res;
- unsigned e_res;
- unsigned sign_res;
- unsigned e1 = (f1 & 0x7f800000) >> 23; //Extract the exponnent bits
- unsigned e2 = (f2 & 0x7f800000) >> 23;
- unsigned long long m1 = (f1 & 0x7fffff) | (1 << 23); //Extract the mantissa bits, add an implicit 1 so it becomes (1 + m1)
- unsigned long long m2 = (f2 & 0x7fffff) | (1 << 23);
- unsigned f1_abs = f1 & 0x7fffffff;
- unsigned f2_abs = f2 & 0x7fffffff;
- unsigned f1_sign = (f1 & 0x80000000) >> 31;//0 if positive, 1 if negative
- unsigned f2_sign = (f2 & 0x80000000) >> 31;
- unsigned result = 0x0;
- // //This is to take care of the NaN case
- if (!(exponent(f1) ^ 0xff) && mantissa(f1)) {
- return f1;
- }
- if (!(exponent(f2) ^ 0xff) && mantissa(f2)) {
- return f2;
- }
- //This is to catch the infinity case
- if (!(exponent(f1) ^ 0xff) && !(exponent(f2) ^ 0xff)) {
- if (diff_sign) {
- return 0x7f800000 + 1;//NaN, Infinity - Infinity
- } else {
- return f1; //Both are either Infinity, or -Infinity, return Infinity
- }
- }
- //Exponent could be negative my guy
- unsigned exp_diff;//Sign difference is also correct
- unsigned f1_bigger_abs;
- if (f1_abs > f2_abs) {
- f1_bigger_abs = 1;
- } else {
- f1_bigger_abs = 0;
- }
- if (e1 > e2) {//Exponent portion is correct, the exponent is NOT dependent on the sign difference
- e_res = e1;
- exp_diff = e1 - e2;
- e1 -= exp_diff;
- m1 <<= exp_diff;
- } else {
- e_res = e2;
- exp_diff = e2 - e1;
- e2 -= exp_diff;
- m2 <<= exp_diff;
- }
- if (f1_bigger_abs) {//if input 1 is bigger than input 2 disregarding sign for now
- if ((f1_sign == 0) && (f2_sign == 0)) {
- m_res = m1 + m2;
- m_res >>= exp_diff - 1;
- if (m_res & 0x1 == 1) {//For rounding purposes
- m_res++;
- }
- m_res >>= 1;
- if ((m_res & (1 << 24)) == 0x1000000) {//If there is a carry
- m_res >>= 1;
- e_res++;
- }
- m_res &= 0x7fffff;//Get rid of the implied bit
- result = (e_res << 23) | (m_res);
- }
- } else {
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement