Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. uint32_t bit_cast(float f) {
  4. uint32_t x;
  5. memcpy(&x, &f, 4);
  6. return x;
  7. }
  8.  
  9. float bit_cast(uint32_t x) {
  10. float f;
  11. memcpy(&f, &x, 4);
  12. return f;
  13. }
  14.  
  15. int get_uexp(uint32_t x) {
  16. return (x >> 23) & 0xFF;
  17. }
  18.  
  19. int get_mant(uint32_t x) {
  20. return x & 0x7FFFFF;
  21. }
  22.  
  23. // Only works with positive numbers.
  24. float add4(float f[4]) {
  25. uint32_t x[4];
  26. int exps[4];
  27. uint32_t mants[4];
  28. uint32_t max_exp = 0;
  29. for (int i = 0; i < 4; i++) {
  30. x[i] = bit_cast(f[i]);
  31. exps[i] = get_uexp(x[i]);
  32. mants[i] = get_mant(x[i]) << 1; // Preserve one extra bit.
  33. if (exps[i] > max_exp) {
  34. max_exp = exps[i];
  35. }
  36. }
  37. uint32_t mant_sum = 0;
  38. for (int i = 0; i < 4; i++) {
  39. mants[i] |= 0x1000000; // put the hidden 1s in there so the mantissa sum works properly.
  40. mants[i] >>= max_exp - exps[i];
  41. mant_sum += mants[i];
  42. }
  43. mant_sum >>= 1; // Chop off the extra bit.
  44.  
  45. // Now they all have the same exponent, max_exp.
  46. // Sum the mantissas, adjust, and reconstruct the float.
  47. while (mant_sum >= 0x1000000) {
  48. mant_sum >>= 1;
  49. max_exp += 1;
  50. }
  51. uint32_t y = (max_exp << 23) | (mant_sum & 0x7FFFFF);
  52. return bit_cast(y);
  53. }
  54.  
  55. int main()
  56. {
  57. std::cout << "Hello World!\n";
  58.  
  59. float a[4] = { 1.0, 1.0, 1.0, 1.0 };
  60. float b[4] = { bit_cast((uint32_t)0x33800000), bit_cast((uint32_t)0x33800000), bit_cast((uint32_t)0x33800000), bit_cast((uint32_t)0x3F800000) };
  61.  
  62. // std::cout << add4(a) << std::endl;
  63. std::cout << add4(b) << " " << bit_cast(add4(b)) << std::endl;
  64.  
  65. printf("%08x", bit_cast(add4(b)));
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement