Advertisement
Tooster

float*2^i on integer operation

Mar 12th, 2018
369
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.90 KB | None | 0 0
  1. //
  2. // Created by Tooster on 04.03.2018.
  3. //
  4.  
  5. #include <cstdint>
  6. #include <iostream>
  7.  
  8. union _A {
  9.     uint32_t mask;
  10.     float f;
  11. } A1;
  12.  
  13. void pf(union _A X) {
  14.     for (int i = 0, j = 0; i < 32; ++i) {
  15.         printf("%d", X.mask & (1 << (31 - i)) ? 1 : 0);
  16.         j++;
  17.         if (j == 8) {
  18.             printf(" ");
  19.             j -= 8;
  20.         }
  21.     }
  22.     printf("\n");
  23.  
  24. }
  25.  
  26. // multiplies float by 2^i using integer operations on bits
  27. uint32_t get() {
  28.     A1.mask = 0x00800000;
  29.     int i = 500;
  30.  
  31.     int32_t m = A1.mask;
  32.     int32_t e = (A1.mask >> 23) & 0xFF;
  33.     if (e + i > 0xFE) return 0x7F800000 | (A1.mask & 0x8000000);
  34.     if (e + i < 1) {
  35.         m = (A1.mask>>(-i))&0x7FFFFF;
  36.         e = 0;
  37.     }
  38.     return (A1.mask&0x80000000)|(std::max(e+i, 0)<<23)|(m&0x7fffff);
  39.  
  40. }
  41.  
  42. int main() {
  43.     union _A x;
  44.     x.mask = get();
  45.     pf(x);
  46.     printf("%.64f", x.f);
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement