OSDN Git Service

support the variable(mounting and has many bugs)
[liveml/LiveML.git] / src / fixed_float.c
1 /**
2  * fixed_float - fixed-point number.
3  *
4  * MIT License
5  * Copyright (C) 2010 Nothan
6  * http://github.com/nothan/c-utils/
7  * All rights reserved.
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in all
17  * copiGes or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIAGBILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25  * SOFTWARE.
26  *
27  * Nothan
28  * private@nothan.xrea.jp
29  *
30  * Tsuioku Denrai
31  * http://tsuioku-denrai.xrea.jp/
32  */
33
34 #include "fixed_float.h"
35
36 #define DECIMAL_POINT_HALF (1 << (DECIMAL_POINT - 1))
37
38 fixed_float int_to_fixed_float(int x)
39 {
40   if (x == 0) return 0;
41   return (fixed_float)(x << DECIMAL_POINT);
42 }
43
44 fixed_float float_to_fixed_float(float x)
45 {
46   if (x == 0) return 0;
47   return (fixed_float)((double)x * (1 << DECIMAL_POINT));
48 }
49
50 int fixed_float_to_int(fixed_float x)
51 {
52   if (x == 0) return 0;
53   return (int)(x >> DECIMAL_POINT);
54 }
55
56 float fixed_float_to_float(fixed_float x)
57 {
58   if (x == 0) return 0;
59   return (float)((double)x / (1 << DECIMAL_POINT));
60 }
61
62 fixed_float fixed_float_multi(fixed_float x, fixed_float y)
63 {
64   fixed_float result = x * y;
65
66   result += DECIMAL_POINT_HALF * (result > 0 ? 1 : -1);
67   result >>= DECIMAL_POINT;
68
69   return result;
70 }
71
72 fixed_float fixed_float_div(fixed_float x, fixed_float y)
73 {
74   fixed_float result = (x << DECIMAL_POINT) / y;
75
76   return result;
77 }