1 /* float.c: Glulxe code for floating-point operations
2 Designed by Andrew Plotkin <erkyrath@eblong.com>
3 http://eblong.com/zarf/glulx/index.html
13 /* This entire file is compiled out if the FLOAT_SUPPORT option is off.
14 (Because we probably can't define a gfloat32 in that case.) */
16 #ifndef FLOAT_NOT_NATIVE
20 /* Check and make sure the native float format is really
21 IEEE-754 single-precision. */
23 if (sizeof(gfloat32) != 4) {
24 fatal_error("gfloat32 is not 32 bits.");
27 if (encode_float((gfloat32)(-1)) != 0xBF800000) {
28 fatal_error("The gfloat32 format of -1 did not match.");
34 /* Encode and decode floats by reinterpret-casting. */
36 glui32 encode_float(gfloat32 val)
39 *(gfloat32 *)(&res) = val;
43 gfloat32 decode_float(glui32 val)
46 *(glui32 *)(&res) = val;
50 #else /* FLOAT_NOT_NATIVE */
57 /* Encode and decode floats by a lot of annoying bit manipulation.
58 The following functions are adapted from code in Python
59 (Objects/floatobject.c). */
61 glui32 encode_float(gfloat32 val)
79 return sign | 0x7f800000; /* infinity */
83 return sign | 0x7fc00000;
86 mant = frexpf(absval, &expo);
88 /* Normalize mantissa to be in the range [1.0, 2.0) */
89 if (0.5 <= mant && mant < 1.0) {
93 else if (mant == 0.0) {
97 return sign | 0x7f800000; /* infinity */
101 return sign | 0x7f800000; /* infinity */
103 else if (expo < -126) {
104 /* Denormalized (very small) number */
105 mant = ldexpf(mant, 126 + expo);
108 else if (!(expo == 0 && mant == 0.0)) {
110 mant -= 1.0; /* Get rid of leading 1 */
113 mant *= 8388608.0; /* 2^23 */
114 fbits = (glui32)(mant + 0.5); /* round mant to nearest int */
116 /* The carry propagated out of a string of 23 1 bits. */
120 return sign | 0x7f800000; /* infinity */
124 return (sign) | ((glui32)(expo << 23)) | (fbits);
127 gfloat32 decode_float(glui32 val)
135 sign = ((val & 0x80000000) != 0);
136 expo = (val >> 23) & 0xFF;
137 mant = val & 0x7FFFFF;
142 return (sign ? (-INFINITY) : (INFINITY));
146 return (sign ? (-NAN) : (NAN));
150 res = (gfloat32)mant / 8388608.0;
159 res = ldexpf(res, expo);
161 return (sign ? (-res) : (res));
164 #endif /* FLOAT_NOT_NATIVE */
166 #endif /* FLOAT_SUPPORT */