KrisLibrary  1.0.0
cast.h
1 #ifndef MATH_CAST_H
2 #define MATH_CAST_H
3 
4 #include <math.h>
5 
6 const static unsigned int OneFloat = 0x3f800000;
7 const static unsigned int FSignMask = 0x80000000;
8 const static unsigned int FExponentMask = 0x7f800000;
9 const static unsigned int FMantissaMask = 0x007fffff;
10 
11 #ifdef WIN32
12 inline long int iRound(float f) { return long int(f); }
13 inline long int iRound(double f) { return long int(f); }
14 #else
15 inline long int iRound(float f) { return lrintf(f); }
16 inline long int iRound(double f) { return lrint(f); }
17 #endif
18 
19 inline long int iFloor(float f) { return iRound(floorf(f)); }
20 inline long int iFloor(double f) { return iRound(floor(f)); }
21 
22 inline long int iCeil(float f) { return iRound(ceilf(f)); }
23 inline long int iCeil(double f) { return iRound(ceil(f)); }
24 
25 inline long int iTrunc(float f) { return (long int)f; }
26 inline long int iTrunc(double f) { return (long int)f; }
27 
28 
29 //converts a fixed-point unsigned char to a float (unsigned char in the range [0,1])
30 inline float FixedByteToFloat(unsigned char x)
31 {
32  static const float scale = 1.0f/255.0f;
33  return float(x)*scale;
34 }
35 
36 //converts a float in the range [0,1] to a fixed-point unsigned char
37 inline unsigned char FloatToFixedByte(float x)
38 {
39  if(x > 255.0f)
40  return 0xff;
41  if(x < 0.0f)
42  return 0;
43 
44  int i = int(x*255.0f);
45  return i&0xff;
46 }
47 
48 //converts a fixed-point unsigned char to a float (unsigned char in the range [0,1) )
49 inline float FixedByteToFloat_Exclusive(unsigned char x)
50 {
51  unsigned int tmp = OneFloat | (x << 15);
52  return (*(float*)&tmp) - 1.0f;
53 }
54 
55 //converts a fixed-point int to a float (int in the range [0,1) )
56 inline float FixedIntToFloat_Exclusive(unsigned long i)
57 {
58  unsigned int tmp = OneFloat | (i >> 9);
59  return (*(float*)&tmp) - 1.0f;
60 }
61 
62 #endif
Common math typedefs, constants, functions.