Advertisement
Guest User

Untitled

a guest
Feb 17th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. unsigned add_floats(unsigned f1, unsigned f2) {
  2. unsigned m_res;
  3. unsigned e_res;
  4. unsigned sign_res;
  5.  
  6. unsigned e1 = (f1 & 0x7f800000) >> 23; //Extract the exponnent bits
  7. unsigned e2 = (f2 & 0x7f800000) >> 23;
  8.  
  9. unsigned long long m1 = (f1 & 0x7fffff) | (1 << 23); //Extract the mantissa bits, add an implicit 1 so it becomes (1 + m1)
  10. unsigned long long m2 = (f2 & 0x7fffff) | (1 << 23);
  11.  
  12. unsigned f1_abs = f1 & 0x7fffffff;
  13. unsigned f2_abs = f2 & 0x7fffffff;
  14.  
  15. unsigned f1_sign = (f1 & 0x80000000) >> 31;//0 if positive, 1 if negative
  16. unsigned f2_sign = (f2 & 0x80000000) >> 31;
  17.  
  18. unsigned result = 0x0;
  19.  
  20. // //This is to take care of the NaN case
  21. if (!(exponent(f1) ^ 0xff) && mantissa(f1)) {
  22. return f1;
  23. }
  24. if (!(exponent(f2) ^ 0xff) && mantissa(f2)) {
  25. return f2;
  26. }
  27.  
  28. //This is to catch the infinity case
  29. if (!(exponent(f1) ^ 0xff) && !(exponent(f2) ^ 0xff)) {
  30. if (diff_sign) {
  31. return 0x7f800000 + 1;//NaN, Infinity - Infinity
  32. } else {
  33. return f1; //Both are either Infinity, or -Infinity, return Infinity
  34. }
  35. }
  36. //Exponent could be negative my guy
  37.  
  38. unsigned exp_diff;//Sign difference is also correct
  39. unsigned f1_bigger_abs;
  40.  
  41. if (f1_abs > f2_abs) {
  42. f1_bigger_abs = 1;
  43. } else {
  44. f1_bigger_abs = 0;
  45. }
  46.  
  47. if (e1 > e2) {//Exponent portion is correct, the exponent is NOT dependent on the sign difference
  48. e_res = e1;
  49. exp_diff = e1 - e2;
  50. e1 -= exp_diff;
  51. m1 <<= exp_diff;
  52. } else {
  53. e_res = e2;
  54. exp_diff = e2 - e1;
  55. e2 -= exp_diff;
  56. m2 <<= exp_diff;
  57. }
  58.  
  59. if (f1_bigger_abs) {//if input 1 is bigger than input 2 disregarding sign for now
  60. if ((f1_sign == 0) && (f2_sign == 0)) {
  61. m_res = m1 + m2;
  62.  
  63. m_res >>= exp_diff - 1;
  64.  
  65. if (m_res & 0x1 == 1) {//For rounding purposes
  66. m_res++;
  67. }
  68.  
  69. m_res >>= 1;
  70.  
  71. if ((m_res & (1 << 24)) == 0x1000000) {//If there is a carry
  72. m_res >>= 1;
  73. e_res++;
  74. }
  75.  
  76. m_res &= 0x7fffff;//Get rid of the implied bit
  77.  
  78. result = (e_res << 23) | (m_res);
  79. }
  80.  
  81. } else {
  82.  
  83. }
  84. return result;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement