Advertisement
Guest User

Half-float to single precision floating point conversion routine

a guest
Apr 6th, 2010
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. union U {
  2.     int i;
  3.     float f;
  4. };
  5.  
  6.  
  7. float h2f(unsigned short y)
  8. {
  9.  
  10.     if (BigEndian)
  11.     y=ToLittleEndian(y);
  12.  
  13.     U value;
  14.  
  15.     int s = (y >> 15) & 0x00000001;
  16.     int e = (y >> 10) & 0x0000001f;
  17.     int m =  y        & 0x000003ff;
  18.  
  19.     if (e == 0)
  20.     {
  21.     if (m == 0)
  22.     {
  23.         //
  24.         // Plus or minus zero
  25.         //
  26.  
  27.         return s << 31;
  28.     }
  29.     else
  30.     {
  31.         //
  32.         // Denormalized number -- renormalize it
  33.         //
  34.  
  35.         while (!(m & 0x00000400))
  36.         {
  37.         m <<= 1;
  38.         e -=  1;
  39.         }
  40.  
  41.         e += 1;
  42.         m &= ~0x00000400;
  43.     }
  44.     }
  45.     else if (e == 31)
  46.     {
  47.     if (m == 0)
  48.     {
  49.         //
  50.         // Positive or negative infinity
  51.         //
  52.  
  53.         return (s << 31) | 0x7f800000;
  54.     }
  55.     else
  56.     {
  57.         //
  58.         // Nan -- preserve sign and significand bits
  59.         //
  60.  
  61.         return (s << 31) | 0x7f800000 | (m << 13);
  62.     }
  63.     }
  64.  
  65.     //
  66.     // Normalized number
  67.     //
  68.  
  69.     e = e + (127 - 15);
  70.     m = m << 13;
  71.  
  72.     //
  73.     // Assemble s, e and m.
  74.     //
  75.  
  76.     value.i = (s << 31) | (e << 23) | m;
  77.     return value.f;
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement