3 * Floating-point format conversions
5 * (c) 2024 Straylight/Edgeware
8 /*----- Licensing notice --------------------------------------------------*
10 * This file is part of the mLib utilities library.
12 * mLib is free software: you can redistribute it and/or modify it under
13 * the terms of the GNU Library General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or (at
15 * your option) any later version.
17 * mLib is distributed in the hope that it will be useful, but WITHOUT
18 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
20 * License for more details.
22 * You should have received a copy of the GNU Library General Public
23 * License along with mLib. If not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
28 /*----- Header files ------------------------------------------------------*/
44 /*----- Preliminary hacking -----------------------------------------------*/
46 /* The native-format conversions are -- at least if the format is
47 * unrecognized -- dependent on the implementation's rounding. Our own
48 * rounding mode specifications don't fit into the framework very well, but I
49 * still want to respect the prevailing rounding mode.
51 * The `proper' way to do this is with %|#pragma STDC FENV_ACCESS|%. But
52 * that doesn't actually work on GCC, or on Clang from not too long ago. So
53 * use compiler-specific hacking to support this.
55 #if GCC_VERSION_P(4, 4)
56 # pragma GCC optimize "-frounding-math"
57 #elif CLANG_VERSION_P(11, 0) && !CLANG_VERSION_P(12, 0)
58 # pragma clang optimize "-frounding-math"
59 #elif GCC_VERSION_P(0, 0) || \
60 (CLANG_VERSION_P(0, 0) && !CLANG_VERSION_P(12, 0))
62 #elif __STDC_VERSION__ >= 199001
64 # pragma STDC FENV_ACCESS ON
67 /*----- Some useful constants ---------------------------------------------*/
69 #define B31 0x80000000u /* just bit 31 */
70 #define B30 0x40000000u /* just bit 30 */
72 #define SH32 4294967296.0 /* 2^32 as floating-point */
74 /*----- Useful macros -----------------------------------------------------*/
76 #define B32(k) ((uint32)1 << (k))
77 #define M32(k) (B32(k) - 1)
79 #define FINITEP(x) (!((x)->f&(FLTF_INF | FLTF_NANMASK | FLTF_ZERO)))
81 /*----- Utility functions -------------------------------------------------*/
85 * Arguments: @uint32 x@ = a 32-bit value
87 * Returns: The number of leading zeros in @x@, i.e., the nonnegative
88 * integer %$n$% such that %$2^{31} \le 2^n x < 2^{32}$%.
89 * Returns a nonsensical value if %$x = 0$%.
92 static unsigned clz32(uint32 x)
96 /* Divide and conquer. If the top half of the bits are clear, then there
97 * must be at least 16 leading zero bits, so accumulate and shift. Repeat
98 * for smaller powers of two.
100 * This ends up returning 31 if %$x = 0$%, but don't rely on this.
102 if (!(x&0xffff0000)) { x <<= 16; n += 16; }
103 if (!(x&0xff000000)) { x <<= 8; n += 8; }
104 if (!(x&0xf0000000)) { x <<= 4; n += 4; }
105 if (!(x&0xc0000000)) { x <<= 2; n += 2; }
106 if (!(x&0x80000000)) { n += 1; }
112 * Arguments: @uint32 x@ = a 32-bit value
114 * Returns: The number of trailing zeros in @x@, i.e., the nonnegative
115 * integer %$n$% such that %$x/2^n$% is an odd integer.
116 * Returns a nonsensical value if %$x = 0$%.
119 static unsigned ctz32(uint32 x)
121 #ifdef CTZ_TRADITIONAL
125 /* Divide and conquer. If the bottom half of the bits are clear, then
126 * there must be at least 16 trailing zero bits, so accumulate and shift.
127 * Repeat for smaller powers of two.
129 * This ends up returning 31 if %$x = 0$%, but don't rely on this.
131 if (!(x&0x0000ffff)) { x >>= 16; n += 16; }
132 if (!(x&0x000000ff)) { x >>= 8; n += 8; }
133 if (!(x&0x0000000f)) { x >>= 4; n += 4; }
134 if (!(x&0x00000003)) { x >>= 2; n += 2; }
135 if (!(x&0x00000001)) { n += 1; }
140 static unsigned char tab[] =
142 ;;; Compute the decoding table for the de Bruijn sequence trick below.
144 (let ((db #x04653adf)
145 (rv (make-vector 32 nil)))
147 (aset rv (logand (ash db (- i 27)) #x1f) i))
149 (goto-char (point-min))
150 (search-forward (concat "***" "BEGIN ctz32tab" "***"))
151 (beginning-of-line 2)
152 (delete-region (point)
154 (search-forward "***END***")
158 (cond ((zerop i) (insert " { "))
159 ((zerop (mod i 16)) (insert ",\n "))
160 ((zerop (mod i 4)) (insert ", "))
162 (insert (format "%2d" (aref rv i))))
166 /* ***BEGIN ctz32tab*** */
167 { 0, 1, 2, 6, 3, 11, 7, 16, 4, 14, 12, 21, 8, 23, 17, 26,
168 31, 5, 10, 15, 13, 20, 22, 25, 30, 9, 19, 24, 29, 18, 28, 27 };
171 /* Sneaky trick. Two's complement negation (which you effectively get
172 * using C unsigned arithmetic, whether you like it or not) complements all
173 * of the bits of an operand more significant than the least significant
174 * set bit. Therefore, this bit is the only one set in both %$x$% and
175 * %$-x$%, so @x&-x@ will isolate it for us.
177 * The magic number @0x04653adf@ is a %%\emph{de Bruijn} number%%: every
178 * group of five consecutive bits is distinct, including groups which `wrap
179 * around', including some low bits and some high bits. Multiplying this
180 * number by a power of two is equivalent to a left shift; and, because the
181 * top five bits are all zero, the most significant five bits of the
182 * product are the same as if we'd applied a rotation. The result is that
183 * we end up with a distinctive pattern in those bits which perfectly
184 * diagnose each shift from 0 up to 31, which we can decode using a table.
186 * David Seal described a similar trick -- using the six-bit pattern
187 * generated by the constant @0x0450fbaf@ -- in `comp.sys.arm' in 1994;
188 * this constant was particularly convenient to multiply by on early ARM
189 * processors. The use of a de Bruijn number is described in Henry
190 * Warren's %%\emph{Hacker's Delight}%%.
192 return (tab[((x&-x)*0x04653adf >> 27)&0x1f]);
197 /* --- @shl@, @shr@ --- *
199 * Arguments: @uint32 *z@ = destination vector
200 * @const uint32 *x@ = source vector
201 * @size_t sz@ = size of source vector, in elements
202 * @unsigned n@ = number of bits to shift by; must be less than
205 * Returns: The bits shifted off the end of the vector.
207 * Use: Shift a vector of 32-bit words left (@shl@) or right (@shr@)
208 * by some number of bit positions. These functions work
209 * correctly if @z@ and @x@ are the same pointer, but not if
210 * they otherwise overlap.
213 static uint32 shl(uint32 *z, const uint32 *x, size_t sz, unsigned n)
220 for (i = 0; i < sz; i++) z[i] = x[i];
224 for (t = 0, i = sz; i--; )
225 { u = x[i]; z[i] = ((u << n) | t)&MASK32; t = u >> r; }
230 static uint32 shr(uint32 *z, const uint32 *x, size_t sz, unsigned n)
237 for (i = 0; i < sz; i++) z[i] = x[i];
241 for (t = 0, i = 0; i < sz; i++)
242 { u = x[i]; z[i] = ((u >> n) | t)&MASK32; t = u << r; }
247 /* --- @sigbits@ --- *
249 * Arguments: @const struct floatbits *x@ = decoded floating-point number
251 * Returns: The number of significant digits in @x@'s fraction. This
252 * will be zero if @x@ is zero or infinite.
255 static unsigned sigbits(const struct floatbits *x)
260 if (x->f&(FLTF_ZERO | FLTF_INF)) return (0);
264 w = x->frac[--i]; if (w) return (32*(i + 1) - ctz32(w));
268 /* --- @ms_set_bit@ --- *
270 * Arguments: @const uint32 *x@ = pointer to the %%\emph{end}%% of the
272 * @unsigned from, to@ = lower (inclusive) and upper (exclusive)
273 * bounds on the region of bits to inspect
275 * Returns: Index of the most significant set bit, or @ALLCLEAR@.
277 * Use: For the (rather unusual) purposes of this function, the bits
278 * of the input are numbered from zero, being the least
279 * significant bit of @x[-1]@, upwards through more significant
280 * bits of @x[-1]@, and then through @x[-2]@ and so on.
282 * If all of the bits in the half-open region are clear then
283 * @ALLCLEAR@ is returned; otherwise, the return value is the
284 * index of the most significant set bit in the region. Note
285 * that @ALLCLEAR@ is equal to @UINT_MAX@: since this is the
286 * largest possible value of @to@, and the upper bound is
287 * exclusive, this cannot be the index of a bit in the region.
290 #define ALLCLEAR UINT_MAX
291 static unsigned ms_set_bit(const uint32 *x, unsigned from, unsigned to)
293 unsigned n0, n, b, base;
296 /* <--- increasing indices <---
298 * ---+-------+-------+-------+-------+-------+---
299 * ...S |///| | | | | |//| S...
300 * ---+-------+-------+-------+-------+-------+---
303 /* If the region is empty then it's technically true that all of the bits
304 * are zero. It's important to be able to answer the case where
305 * %$\id{from} = \id{to} = 0$% without accessing memory.
307 assert(to >= from); if (to == from) return (ALLCLEAR);
309 /* This is distressingly complicated. Here's how it's going to work.
311 * There's at least one bit to check, or we'd have returned already --
312 * specifically, we must check the bit with index @from@. But that's at
313 * the wrong end. Instead, we start at the most significant end, with the
314 * word containing the bit one short of the @to@ position. Even though
315 * it's actually one off, because we use a half-open interval, we'll call
316 * that the `@to@ bit'.
318 * We start by loading the word containing the @to@ bit, and start @base@
319 * off as the bit index of the least significant bit of this word. We mask
320 * off the high bits (if any), leaving only the @to@ bit and the less
321 * significant ones. We %%\emph{don't}%% check the remaining bits yet.
323 * We then start an offset loop. In each iteration, we check the word
324 * we're currently holding: if it's not zero, then we return @base@ plus
325 * the position of the most-significant set bit, using @clz32@. Otherwise,
326 * we load the next (less significant) word, and drop @base@ by 32, but
327 * don't check it yet. We end this loop when the word we're holding
328 * contains the @from@ bit. It's possible that we didn't do any iterations
329 * of the loop, in which case we're still holding the word containing the
330 * @to@ bit at this point.
332 * Finally, we mask off the bits below the @from@ bit, and check that what
333 * we have left is zero. If it isn't, we return @base@ plus the position
334 * of the most significant bit; if it is, we return @ALLCEAR@.
337 /* The first job is to find the word containing the @to@ bit and mask off
338 * any higher bits that we don't care about.
340 * Recall that the bit's index is @to - 1@, but this must be a valid index
341 * because there is at least one bit in the region. But we start out
342 * pointing beyond the vector, so we must add an extra 32 bits.
344 n0 = (to + 31)/32; x -= n0; base = (to - 1)&~31u; w = *x++;
345 b = to%32; if (b) w &= M32(b);
347 /* Before we start the loop, it'd be useful to know how many iterations we
348 * need. This is going to be the offset from the word containing the @to@
349 * bit to the word containing the @from@ bit. Again, we're off by one
350 * because that's how our initial indexing is set up.
352 n = n0 - from/32 - 1;
354 /* Now it's time to do the loop. This is the easy bit. */
356 if (w) return (base + 31 - clz32(w));
357 w = *x++&MASK32; base -= 32;
360 /* We're now holding the final word -- the one containing the @from@ bit.
361 * We need to mask off any low bits that we don't care about.
363 m = M32(from%32); w &= MASK32&~m;
366 if (w) return (base + 31 - clz32(w));
367 else return (ALLCLEAR);
370 /*----- General floating-point hacking ------------------------------------*/
372 /* --- @fltfmt_initbits@ --- *
374 * Arguments: @struct floatbits *x@ = pointer to structure to initialize
378 * Use: Dynamically initialize @x@ to (positive) zero so that it can
379 * be used as the destination operand by other operations. This
380 * doesn't allocate resources and cannot fail. The
381 * @FLOATBITS_INIT@ macro is a suitable static initializer for
382 * performing the same task.
385 void fltfmt_initbits(struct floatbits *x)
389 x->frac = 0; x->n = x->fracsz = 0;
392 /* --- @fltfmt_freebits@ --- *
394 * Arguments: @struct floatbits *x@ = pointer to structure to free
398 * Use: Releases the memory held by @x@. Afterwards, @x@ is a valid
399 * (positive) zero, but can safely be discarded.
402 void fltfmt_freebits(struct floatbits *x)
404 if (x->frac) x_free(x->a, x->frac);
406 x->frac = 0; x->n = x->fracsz = 0;
409 /* --- @fltfmt_allocfrac@ --- *
411 * Arguments: @struct floatbits *x@ = structure to adjust
412 * @unsigned n@ = number of words required
416 * Use: Reallocate the @frac@ vector so that it has space for at
417 * least @n@ 32-bit words, and set @x->n@ equal to @n@. If the
418 * current size is already @n@ or greater, then just update the
419 * active length @n@ and return; otherwise, any existing vector
420 * is discarded and a fresh, larger one allocated.
423 void fltfmt_allocfrac(struct floatbits *x, unsigned n)
424 { GROWBUF_REPLACEV(unsigned, x->a, x->frac, x->fracsz, n, 4); x->n = n; }
426 /* --- @fltfmt_copybits@ --- *
428 * Arguments: @struct floatbits *z_out@ = where to leave the result
429 * @const struct floatbits *x@ = source to copy
433 * Use: Make @z_out@ be a copy of @x@. If @z_out@ is the same object
434 * as @x@ then do nothing.
437 void fltfmt_copybits(struct floatbits *z_out, const struct floatbits *x)
441 if (z_out == x) return;
443 if (!FINITEP(x)) z_out->exp = 0;
444 else z_out->exp = x->exp;
445 if ((x->f&(FLTF_ZERO | FLTF_INF)) || !x->n)
446 { z_out->n = 0; z_out->frac = 0; }
448 fltfmt_allocfrac(z_out, x->n);
449 for (i = 0; i < x->n; i++) z_out->frac[i] = x->frac[i];
453 /* --- @fltfmt_round@ --- *
455 * Arguments: @struct floatbits *z_out@ = destination (may equal source)
456 * @const struct floatbits *x@ = source
457 * @unsigned r@ = rounding mode (@FLTRND_...@ code)
458 * @unsigned n@ = nonzero number of bits to leave
460 * Returns: A @FLTERR_...@ code, specifically either @FLTERR_INEXACT@ if
461 * rounding discarded some nonzero value bits, or @FLTERR_OK@ if
462 * rounding was unnecessary.
464 * Use: Rounds a floating-point value to a given number of
465 * significant bits, using the given rounding rule.
468 unsigned fltfmt_round(struct floatbits *z_out, const struct floatbits *x,
469 unsigned r, unsigned n)
471 unsigned rf, i, uw, ub, hw, hb, rc = 0;
475 /* Check that this is likely to work. We must have at least one bit
476 * remaining, so that we can inspect the last-place unit bit. And we
477 * mustn't round up if the current value is already exact, because that
478 * would be nonsensical (and inconvenient).
480 assert(n > 0); assert(!(r&~(FRPMASK_LOW | FRPMASK_HALF)));
482 /* Eliminate trivial cases. There's nothing to do if the value is infinite
483 * or zero, or if we don't have enough precision already.
485 * The caller will have set the rounding mode and length suitably for a
488 if (x->f&(FLTF_ZERO | FLTF_INF) || n >= 32*x->n)
489 { fltfmt_copybits(z_out, x); return (FLTERR_OK); }
491 /* Determine various indices.
493 * The quantities @uw@ and @ub@ are the word and bit number which will hold
494 * the unit bit when we've finished; @hw@ and @hb@ similarly index the
495 * `half' bit, which is the next less significant bit.
497 uw = (n - 1)/32; ub = -n&31;
498 if (!ub) { hw = uw + 1; hb = 31; }
499 else { hw = uw; hb = ub - 1; }
501 /* Determine the necessary predicates for the rounding decision. */
503 if (x->f&FLTF_NEG) rf |= FRPF_NEG;
504 um = B32(ub); if (x->frac[uw]&um) rf |= FRPF_ODD;
505 hm = B32(hb); if (x->frac[hw]&hm) rf |= FRPF_HALF;
506 if (x->frac[hw]&(hm - 1)) rf |= FRPF_LOW;
507 for (i = hw + 1; i < x->n; i++) if (x->frac[i]) rf |= FRPF_LOW;
508 if (rf&(FRPF_LOW | FRPF_HALF)) rc |= FLTERR_INEXACT;
510 /* Allocate space for the result. */
511 fltfmt_allocfrac(z_out, uw + 1);
513 /* We start looking at the least significant word of the result. Clear the
516 i = uw; exp = x->exp; w = x->frac[i]&~(um - 1);
518 /* If the rounding function is true then we need to add one to the
519 * truncated fraction and propagate carries.
525 w = (x->frac[--i] + 1)&MASK32;
527 if (!w) { w = B31; exp++; }
530 /* Store, and copy the remaining words. */
538 z_out->f = x->f&(FLTF_NEG | FLTF_NANMASK);
539 if (x->f&FLTF_NANMASK) z_out->exp = 0;
540 else z_out->exp = exp;
544 /*----- IEEE and related formats ------------------------------------------*/
546 /* IEEE (and related) format descriptions. */
547 const struct fltfmt_ieeefmt
548 fltfmt_mini = { FLTIF_HIDDEN, 4, 4 },
549 fltfmt_bf16 = { FLTIF_HIDDEN, 8, 8 },
550 fltfmt_f16 = { FLTIF_HIDDEN, 5, 11 },
551 fltfmt_f32 = { FLTIF_HIDDEN, 8, 24 },
552 fltfmt_f64 = { FLTIF_HIDDEN, 11, 53 },
553 fltfmt_f128 = { FLTIF_HIDDEN, 15, 113 },
554 fltfmt_idblext80 = { 0, 15, 64 };
556 /* --- @fltfmt_encieee@ ---
558 * Arguments: @const struct fltfmt_ieeefmt *fmt@ = format description
559 * @uint32 *z@ = output vector
560 * @const struct floatbits *x@ = value to encode
561 * @unsigned r@ = rounding mode
562 * @unsigned errmask@ = error mask
564 * Returns: Error flags (@FLTERR_...@).
566 * Use: Encode a floating-point value in an IEEE format. This is the
567 * machinery shared by the @fltfmt_enc...@ functions for
568 * encoding IEEE-format values. Most of the arguments and
569 * behaviour are as described for those functions.
571 * The encoded value is right-aligned and big-endian; i.e., the
572 * sign bit ends up in @z[0]@, and the least significant bit of
573 * the significand ends up in the least significant bit of
577 unsigned fltfmt_encieee(const struct fltfmt_ieeefmt *fmt,
578 uint32 *z, const struct floatbits *x,
579 unsigned r, unsigned errmask)
582 unsigned sigwd, fracwd, err = 0, f = x->f, rf;
583 unsigned i, j, n, nb, nw, mb, mw, esh, sh;
584 int exp, minexp, maxexp;
587 #define ERR(e) do { err |= (e); if (err&~errmask) goto end; } while (0)
589 /* The following code assumes that the sign, biased exponent, unit, and
590 * quiet/signalling bits can all fit into the most significant 32 bits of
593 assert(fmt->expwd + 3 <= 32);
594 esh = 31 - fmt->expwd;
596 /* Determine the output size. */
597 nb = fmt->prec + fmt->expwd + 1;
598 if (fmt->f&FLTIF_HIDDEN) nb--;
601 /* Determine the top bits. */
603 if (x->f&FLTF_NEG) z0 |= B31;
605 /* And now for the main case analysis. */
608 /* Zero. There's very little to do here. */
610 } else if (f&FLTF_INF) {
611 /* Infinity. Set the exponent and, for non-hidden-bit formats, the unit
615 z0 |= M32(fmt->expwd) << esh;
616 if (!(fmt->f&FLTIF_HIDDEN)) z0 |= B32(esh - 1);
618 } else if (f&FLTF_NANMASK) {
621 * We must check that we won't lose significant bits. We need a bit for
622 * the quiet/signalling flag, and enough space for the significant
623 * payload bits. The unit bit is not in play here, so the available
624 * space is always one less than the advertised precision. To put it
625 * another way, we need space for the payload, a bit for the
626 * quiet/signalling flag, and a bit for the unit place.
630 if (fracwd + 2 > fmt->prec) ERR(FLTERR_INEXACT);
634 * If the payload is all-zero and we're meant to set a signalling NaN
635 * then report an exactness failure and set the least-significant bit.
637 mb = fmt->prec - 2; mw = (mb + 31)/32; sh = -mb%32;
640 else { n = mw; j = sh; }
641 if ((f&FLTF_SNAN) && ms_set_bit(x->frac + n, j, 32*n) == ALLCLEAR) {
643 n = nw - 1; for (i = 0; i < n; i++) z[i] = 0;
646 for (i = 0; i < nw - mw; i++) z[i] = 0;
647 n = x->n; if (n > mw) n = mw;
648 t = shr(z + i, x->frac, n, sh); i += n;
649 if (i < nw) z[i++] = t;
650 sh = esh - 2; if (fmt->f&FLTIF_HIDDEN) sh++;
651 if (f&FLTF_QNAN) z0 |= B32(sh);
654 /* Set the exponent and, for non-hidden-bit formats, the unit bit. */
655 z0 |= M32(fmt->expwd) << esh;
656 if (!(fmt->f&FLTIF_HIDDEN)) z0 |= B32(esh - 1);
661 * Adjust the exponent by one place to compensate for the difference in
662 * significant conventions. Our significand lies between zero (in fact,
663 * a half, because we require normalization) and one, while an IEEE
664 * significand lies between zero (in fact, one) and two. Our exponent is
665 * therefore one larger than the IEEE exponent will be.
668 /* Determine the maximum true (unbiased) exponent. As noted above, this
672 maxexp = (1 << (fmt->expwd - 1)) - 1;
675 if (exp <= minexp - (int)fmt->prec) {
676 /* If the exponent is very small then we underflow. We have %$p - 1$%
677 * bits available to represent a subnormal significand, and therefore
678 * can represent at least one bit of a value as small as
679 * %$2^{e_{\text{min}}-p+1}$%.
681 * If the exponent is one short of the threshold, then we check to see
682 * whether the value will round up.
685 if ((minexp - exp == fmt->prec) &&
687 (sigbits(x) > 1 ? FRPF_LOW : 0) |
688 (f&FLTF_NEG ? FRPF_NEG : 0)))&1)) {
690 for (i = 0; i < nw - 1; i++) z[i] = 0;
693 ERR(FLTERR_UFLOW | FLTERR_INEXACT);
694 /* Return (signed) zero. */
698 /* We can at least try to store some bits. */
700 /* Let's see how many we need to deal with and how much space we have.
701 * We might as well set the biased exponent here while we're at it.
703 * If %$e \ge e_{\text{min}}$% then we can store %$p$% bits of
704 * significand. Otherwise, we must make a subnormal and we can only
705 * store %$p + e - e_{\text{min}}$% bits. (Cross-check: if %$e \le
706 * e_{\text{min}} - p$% then we can store zero bits or fewer and have
707 * underflowed to zero, which matches the previous case.) In the
708 * subnormal case, we also `correct' the exponent so that we store the
709 * correct sentinel value later.
712 if (exp >= minexp) sigwd = fmt->prec;
713 else { sigwd = fmt->prec + exp - minexp; exp = minexp - 1; }
714 mw = (sigwd + 31)/32; sh = -sigwd%32;
716 /* If we don't have enough significand bits then we must round. This
717 * might increase the exponent, so we must reload.
719 if (fracwd > sigwd) {
721 y.frac = z + nw - mw; y.fracsz = mw; fltfmt_round(&y, x, r, sigwd);
722 x = &y; exp = y.exp - 1; fracwd = sigwd;
726 /* If the exponent is too large, then we overflow. If the error is
727 * masked, then we must produce a default value, choosing between
728 * infinity and the largest representable finite value according to
732 ERR(FLTERR_OFLOW | FLTERR_INEXACT);
733 rf = FRPF_ODD | FRPF_HALF | FRPF_LOW;
734 if (f&FLTF_NEG) rf |= FRPF_NEG;
736 z0 |= M32(fmt->expwd) << esh;
738 z0 |= (B32(fmt->expwd) - 2) << esh;
739 mb = fmt->prec; if (fmt->f&FLTIF_HIDDEN) mb--;
743 while (i < nw) z[i++] = MASK32;
747 /* The exponent is in range. Everything is ready. */
749 /* Store the significand. */
750 n = (fracwd + 31)/32; i = nw - mw;
751 t = shr(z + i, x->frac, n, sh); i += n;
752 if (i < nw) z[i++] = t;
754 /* Fill in the top end. */
755 for (j = nw - mw; j--; ) z[j] = 0;
757 /* Set the biased exponent. */
758 z0 |= (exp + maxexp) << esh;
760 /* Clear the unit bit if we're suppose to use a hidden-bit
763 if (fmt->f&FLTIF_HIDDEN) {
764 mb = fmt->prec - 1; mw = (mb + 31)/32; mb = mb%32;
765 z[nw - mw] &= ~B32(mb);
771 /* Clear the significand bits that we haven't set explicitly yet. */
772 while (i < nw) z[i++] = 0;
774 /* All that remains is to insert the top bits @z0@ in the right place.
775 * This will set the exponent, and the unit and quiet bits.
779 if (sh && nb >= 32) z[1] |= z0 << (32 - sh);
787 /* --- @fltfmt_encTY@ --- *
789 * Arguments: @octet *z_out@, @uint16 *z_out@, @uint32 *z_out@,
790 * @kludge64 *z_out@ = where to put the encoded value
791 * @uint16 *se_out@, @kludge64 *m_out@ = where to put the
792 * encoded sign-and-exponent and significand
793 * @const struct floatbits *x@ = value to encode
794 * @unsigned r@ = rounding mode
795 * @unsigned errmask@ = error mask
797 * Returns: Error flags (@FLTERR_...@).
799 * Use: Encode a floating-point value in an IEEE (or IEEE-adjacent)
802 * If an error is encountered during the encoding, and the
803 * corresponding bit of @errmask@ is clear, then processing
804 * stops immediately and the error is returned; if the bit is
805 * set, then processing continues as described below.
809 * * @mini@ for the 8-bit `1.4.3 minifloat' format, with
810 * four-bit exponent and four-bit significand, represented
813 * * @bf16@ for the Google `bfloat16' format, with eight-bit
814 * exponent and eight-bit significand, represented as a
817 * * @f16@ for the IEEE `binary16' format, with five-bit
818 * exponent and eleven-bit significand, represented as a
821 * * @f32@ for the IEEE `binary32' format, with eight-bit
822 * exponent and 24-bit significand, represented as a
825 * * @f64@ for the IEEE `binary64' format, with eleven-bit
826 * exponent and 53-bit significand, represented as a
829 * * @f128@ for the IEEE `binary128' format, with fifteen-bit
830 * exponent and 113-bit significand, represented as four
831 * @uint32@ limbs, most significant first; or
833 * * @idblext80@ for the Intel 80-bit `double extended'
834 * format, with fifteen-bit exponent and 64-bit significand
835 * with no hidden bit, represented as a @uint16 se@
836 * holding the sign and exponent, and a @kludge64 m@
837 * holding the significand.
839 * Positive and negative zero and infinity are representable
842 * Following IEEE recommendations (and most implementations),
843 * the most significant fraction bit of a quiet NaN is set; this
844 * bit is clear in a signalling NaN. The most significant
845 * payload bits of a NaN, held in the top bits of @x->frac[0]@,
846 * are encoded in the output significand following the `quiet'
847 * bit. If the chosen format's significand field is too small
848 * to accommodate all of the set payload bits then the
849 * @FLTERR_INEXACT@ error bit is set and, if masked, the
850 * excess payload bits are discarded. No rounding of NaN
851 * payloads is performed.
853 * Otherwise, the input value is finite and nonzero. If the
854 * significand cannot be represented exactly then the
855 * @FLTERR_INEXACT@ error bit is set, and, if masked, the value
856 * will be rounded (internally -- the input @x@ is not changed).
857 * If the (rounded) value's exponent is too large to represent,
858 * then the @FLTERR_OFLOW@ and @FLTERR_INEXACT@ error bits are
859 * set and, if masked, the result is either the (absolute)
860 * largest representable finite value or infinity, with the
861 * appropriate sign, chosen according to the rounding mode. If
862 * the exponent is too small to represent, then the
863 * @FLTERR_UFLOW@ and @FLTERR_INEXACT@ error bits are set and,
864 * if masked, the result is either the (absolute) smallest
865 * nonzero value or zero, with the appropriate sign, chosen
866 * according to the rounding mode.
869 unsigned fltfmt_encmini(octet *z_out, const struct floatbits *x,
870 unsigned r, unsigned errmask)
875 rc = fltfmt_encieee(&fltfmt_mini, t, x, r, errmask);
876 if (!(rc&~errmask)) *z_out = t[0];
880 unsigned fltfmt_encbf16(uint16 *z_out, const struct floatbits *x,
881 unsigned r, unsigned errmask)
886 rc = fltfmt_encieee(&fltfmt_bf16, t, x, r, errmask);
887 if (!(rc&~errmask)) *z_out = t[0];
891 unsigned fltfmt_encf16(uint16 *z_out, const struct floatbits *x,
892 unsigned r, unsigned errmask)
897 rc = fltfmt_encieee(&fltfmt_f16, t, x, r, errmask);
898 if (!(rc&~errmask)) *z_out = t[0];
902 unsigned fltfmt_encf32(uint32 *z_out, const struct floatbits *x,
903 unsigned r, unsigned errmask)
904 { return (fltfmt_encieee(&fltfmt_f32, z_out, x, r, errmask)); }
906 unsigned fltfmt_encf64(kludge64 *z_out, const struct floatbits *x,
907 unsigned r, unsigned errmask)
912 rc = fltfmt_encieee(&fltfmt_f64, t, x, r, errmask);
913 if (!(rc&~errmask)) SET64(*z_out, t[0], t[1]);
917 unsigned fltfmt_encf128(uint32 *z_out, const struct floatbits *x,
918 unsigned r, unsigned errmask)
919 { return (fltfmt_encieee(&fltfmt_f128, z_out, x, r, errmask)); }
921 unsigned fltfmt_encidblext80(uint16 *se_out, kludge64 *m_out,
922 const struct floatbits *x,
923 unsigned r, unsigned errmask)
928 rc = fltfmt_encieee(&fltfmt_idblext80, t, x, r, errmask);
929 if (!(rc&~errmask)) { *se_out = t[0]; SET64(*m_out, t[1], t[2]); }
933 /* --- @fltfmt_decieee@ --- *
935 * Arguments: @const struct fltfmt_ieeefmt *fmt@ = format description
936 * @struct floatbits *z_out@ = output decoded representation
937 * @const uint32 *x@ = input encoding
939 * Returns: Error flags (@FLTERR_...@).
941 * Use: Decode a floating-point value in an IEEE format. This is the
942 * machinery shared by the @fltfmt_dec...@ functions for
943 * deccoding IEEE-format values. Most of the arguments and
944 * behaviour are as described for those functions.
946 * The encoded value should be right-aligned and big-endian;
947 * i.e., the sign bit ends up in @z[0]@, and the least
948 * significant bit of the significand ends up in the least
949 * significant bit of @z[n - 1]@.
952 unsigned fltfmt_decieee(const struct fltfmt_ieeefmt *fmt,
953 struct floatbits *z_out, const uint32 *x)
955 unsigned sigwd, err = 0, f = 0;
956 unsigned i, nb, nw, mw, esh, sh;
957 int exp, minexp, maxexp;
958 uint32 x0, t, u, emask;
960 /* The following code assumes that the sign, biased exponent, unit, and
961 * quiet/signalling bits can all fit into the most significant 32 bits of
964 assert(fmt->expwd + 3 <= 32);
965 esh = 31 - fmt->expwd; emask = M32(fmt->expwd);
966 sigwd = fmt->prec; if (fmt->f&FLTIF_HIDDEN) sigwd--;
968 /* Determine the input size. */
969 nb = sigwd + fmt->expwd + 1; nw = (nb + 31)/32;
971 /* Extract the sign, exponent, and top of the significand. */
974 if (sh && nb >= 32) x0 |= x[1] >> (32 - sh);
975 if (x0&B31) f |= FLTF_NEG;
976 t = (x0 >> esh)&emask;
978 /* Time for a case analysis. */
983 * Note that we don't include the quiet bit in our decoded payload.
986 if (!(fmt->f&FLTIF_HIDDEN)) {
987 /* No hidden bit, so we expect the unit bit to be set. If it isn't,
988 * that's technically invalid, and its absence won't survive a round
989 * trip, since the bit isn't considered part of a NaN payload -- or
990 * even to distinguish a NaN from an infinity. In any event, reduce
991 * the notional significand size to exclude this bit from further
995 if (!(x0&B32(esh - 1))) err = FLTERR_INVAL;
999 if (ms_set_bit(x + nw, 0, sigwd) == ALLCLEAR)
1002 sh = esh - 2; if (fmt->f&FLTIF_HIDDEN) sh++;
1003 if (x0&B32(sh)) f |= FLTF_QNAN;
1004 else f |= FLTF_SNAN;
1005 sigwd--; mw = (sigwd + 31)/32;
1006 fltfmt_allocfrac(z_out, mw);
1007 shl(z_out->frac, x + nw - mw, mw, -sigwd%32);
1012 /* Determine the exponent bounds. */
1013 maxexp = (1 << (fmt->expwd - 1)) - 1;
1014 minexp = 1 - maxexp;
1016 /* Dispatch. If there's a hidden bit then everything is well defined.
1017 * Otherwise, we'll normalize the incoming value regardless, but report
1018 * settings of the unit bit which are inconsistent with the exponent.
1020 if (fmt->f&FLTIF_HIDDEN) {
1021 if (!t) { exp = minexp; goto normalize; }
1022 else { exp = t - maxexp; goto hidden; }
1024 u = x0&B32(esh - 1);
1025 if (!t) { exp = minexp; if (u) err |= FLTERR_INVAL; }
1026 else { exp = t - maxexp; if (!u) err |= FLTERR_INVAL; }
1031 /* We have a normal real number with a hidden bit. */
1033 mw = (sigwd + 31)/32;
1036 /* The bits we have occupy a whole number of words, but we need to shift
1037 * to make space for the unit bit.
1040 fltfmt_allocfrac(z_out, mw + 1);
1041 z_out->frac[mw] = shr(z_out->frac, x + nw - mw, mw, 1);
1043 fltfmt_allocfrac(z_out, mw);
1044 shl(z_out->frac, x + nw - mw, mw, -(sigwd + 1)%32);
1046 z_out->frac[0] |= B31;
1047 z_out->exp = exp + 1;
1051 /* We have, at least potentially, a subnormal number, with no hidden
1055 i = ms_set_bit(x + nw, 0, sigwd);
1056 if (i == ALLCLEAR) { f |= FLTF_ZERO; goto end; }
1057 mw = i/32 + 1; sh = 32*mw - i - 1;
1058 fltfmt_allocfrac(z_out, mw);
1059 shl(z_out->frac, x + nw - mw, mw, sh);
1060 z_out->exp = exp - fmt->prec + 2 + i;
1065 z_out->f = f; return (err);
1068 /* --- @fltfmt_decTY@ --- *
1070 * Arguments: @const struct floatbits *z_out@ = storage for the result
1071 * @octet x@, @uint16 x@, @uint32 x@, @kludge64 x@ =
1073 * @uint16 se@, @kludge64 m@ = encoded sign-and-exponent and
1076 * Returns: Error flags (@FLTERR_...@).
1078 * Use: Encode a floating-point value in an IEEE (or IEEE-adjacent)
1081 * The options for @TY@ are as documented for the encoding
1084 * In formats without a hidden bit -- currently only @idblext80@
1085 * -- not all bit patterns are valid encodings. If the explicit
1086 * unit bit is set when the exponent field is all-bits-zero, or
1087 * clear when the exponent field is not all-bits-zero, then the
1088 * @FLTERR_INVAL@ error bit is set. If the exponent is all-
1089 * bits-set, denoting infinity or a NaN, then the unit bit is
1090 * otherwise ignored -- in particular, it does not affect the
1091 * NaN payload, or even whether the input encodes a NaN or
1092 * infinity. Otherwise, the unit bit is considered significant,
1093 * and the result is normalized as one would expect.
1094 * Consequently, biased exponent values 0 and 1 are distinct
1095 * only with respect to which bit patterns are considered valid,
1096 * and not with respect to the set of values denoted.
1099 unsigned fltfmt_decmini(struct floatbits *z_out, octet x)
1100 { uint32 t[1]; t[0] = x; return (fltfmt_decieee(&fltfmt_mini, z_out, t)); }
1102 unsigned fltfmt_decbf16(struct floatbits *z_out, uint16 x)
1103 { uint32 t[1]; t[0] = x; return (fltfmt_decieee(&fltfmt_bf16, z_out, t)); }
1105 unsigned fltfmt_decf16(struct floatbits *z_out, uint16 x)
1106 { uint32 t[1]; t[0] = x; return (fltfmt_decieee(&fltfmt_f16, z_out, t)); }
1108 unsigned fltfmt_decf32(struct floatbits *z_out, uint32 x)
1109 { uint32 t[1]; t[0] = x; return (fltfmt_decieee(&fltfmt_f32, z_out, t)); }
1111 unsigned fltfmt_decf64(struct floatbits *z_out, kludge64 x)
1115 t[0] = HI64(x); t[1] = LO64(x);
1116 return (fltfmt_decieee(&fltfmt_f64, z_out, t));
1119 unsigned fltfmt_decf128(struct floatbits *z_out, const uint32 *x)
1120 { return (fltfmt_decieee(&fltfmt_f128, z_out, x)); }
1122 unsigned fltfmt_decidblext80(struct floatbits *z_out, uint16 se, kludge64 m)
1126 t[0] = se; t[1] = HI64(m); t[2] = LO64(m);
1127 return (fltfmt_decieee(&fltfmt_idblext80, z_out, t));
1130 /*----- Native formats ----------------------------------------------------*/
1132 /* If the floating-point radix is a power of two, determine how many bits
1133 * there are in each digit. This isn't exhaustive, but it covers most of the
1134 * bases, so to speak.
1137 # define DIGIT_BITS 1
1138 #elif FLT_RADIX == 4
1139 # define DIGIT_BITS 2
1140 #elif FLT_RADIX == 8
1141 # define DIGIT_BITS 3
1142 #elif FLT_RADIX == 16
1143 # define DIGIT_BITS 4
1146 /* Take note if we need to cope with the revered quiet/signalling convention
1147 * used by HP-PA and older MIPS processors.
1149 #if defined(__hppa__) || (defined(__mips__) && !defined(__mips_nan2008))
1153 /* --- @ENCFLT@ --- *
1155 * Arguments: @ty@ = the C type to encode
1156 * @TY@ = the uppercase prefix for macros
1157 * @ty (*ldexp)(ty, int)@ = function to scale a @ty@ value by a
1159 * @unsigned &rc@ = error code to set
1160 * @ty *z_out@ = storage for the result
1161 * @const struct floatbits *x@ = value to convert
1162 * @unsigned r@ = rounding mode
1166 * Use: Encode a floating-point value @x@ as a native C object of
1167 * type @ty@. This is the machinery shared by the
1168 * @fltfmt_enc...@ functions for enccoding native-format values.
1169 * Most of the behaviour is as described for those functions.
1172 /* Utilities based on conditional compilation, because we can't use
1173 * %|#ifdef|% directly in macros.
1177 /* The C implementation acknowledges the existence of (quiet) NaN values,
1178 * but will neither let us set the payload in a useful way, nor
1179 * acknowledge the existence of signalling NaNs. We have no good way to
1180 * determine which NaN the @NAN@ macro produces, so report this conversion
1184 # define SETNAN(rc, z) do { (z) = NAN; (rc) = FLTERR_INEXACT; } while (0)
1186 /* This C implementation doesn't recognize NaNs. This value is totally
1187 * unrepresentable, so just report the error. (Maybe it's C89 and would
1188 * actually do the right thing with @0/0@. I'm not sure the requisite
1189 * compile-time configuration machinery is worth the effort.)
1192 # define SETNAN(rc, z) do { (z) = 0; (rc) = FLTERR_REPR; } while (0)
1196 /* The C implementation supports infinities. This is a simple win. */
1198 # define SETINF(TY, rc, z) \
1199 do { (z) = INFINITY; (rc) = FLTERR_OK; } while (0)
1201 /* The C implementation doesn't support infinities. Return the maximum
1202 * value and report it as an overflow; I think this is more useful than
1203 * reporting a complete representation failure. (Maybe it's C89 and would
1204 * actually do the right thing with @1/0@. Again, I'm not sure the
1205 * requisite compile-time configuration machinery is worth the effort.)
1208 # define SETINF(TY, rc, z) do { \
1210 (rc) = FLTERR_OFLOW | FLTERR_INEXACT; \
1215 /* The floating point formats use a power-of-two radix. This means that
1216 * we can determine the correctly rounded value before we start building
1217 * the native floating-point value.
1220 # define ENC_ROUND_DECLS struct floatbits _y;
1221 # define ENC_ROUND(TY, rc, x, r) do { \
1222 (rc) |= fltfmt_round(&_y, (x), (r), DIGIT_BITS*TY##_MANT_DIG); \
1226 /* The floating point formats use a non-power-of-two radix. This means
1227 * that conversion is inherently inexact.
1230 # define ENC_ROUND_DECLS
1231 # define ENC_ROUND(TY, rc, x, r) \
1232 do (rc) |= FLTERR_INEXACT; while (0)
1233 # define ENC_FIXUP(...)
1238 /* The native floating point format uses the opposite quiet-vs-signalling
1239 * NaN convention from the recommended `quiet bit' convention, so the bit
1240 * needs hacking on input.
1243 # define FROBNAN_ENCDECLS struct floatbits _y
1244 # define FROBNAN_ENC do { \
1245 if (_x->f&FLTF_NANMASK) { \
1246 _y.f = _x->f ^ FLTF_NANMASK; _y.frac = _x->frac; _y.n = _x->n; \
1251 /* The native floating point format either uses the conventional
1252 * `quiet-bit' convention, or isn't IEEE at all. Either way, there's
1253 * nothing to do here.
1256 # define FROBNAN_ENCDECLS
1257 # define FROBNAN_ENC do ; while (0)
1260 #define ENCFLT(ty, TY, ldexp, rc, z_out, x, r) do { \
1261 const struct floatbits *_x = (x); \
1265 /* See if the native format is one that we recognize. */ \
1266 switch (TY##_FORMAT&(FLTFMT_ORGMASK | FLTFMT_TYPEMASK)) { \
1268 case FLTFMT_IEEE_F32: { \
1270 unsigned char *_z = (unsigned char *)(z_out); \
1273 (rc) = fltfmt_encieee(&fltfmt_f32, _t, _x, (r), FLTERR_ALLERRS); \
1274 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1275 case FLTFMT_BE: STORE32_B(_z, _t[0]); break; \
1276 case FLTFMT_LE: STORE32_L(_z, _t[0]); break; \
1277 default: assert(!"unimplemented byte order"); break; \
1281 case FLTFMT_IEEE_F64: { \
1283 unsigned char *_z = (unsigned char *)(z_out); \
1286 (rc) = fltfmt_encieee(&fltfmt_f64, _t, _x, (r), FLTERR_ALLERRS); \
1287 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1289 STORE32_B(_z + 0, _t[0]); STORE32_B(_z + 4, _t[1]); \
1292 STORE32_L(_z + 0, _t[1]); STORE32_L(_z + 4, _t[0]); \
1295 STORE32_L(_z + 0, _t[0]); STORE32_L(_z + 4, _t[1]); \
1297 default: assert(!"unimplemented byte order"); break; \
1301 case FLTFMT_IEEE_F128: { \
1303 unsigned char *_z = (unsigned char *)(z_out); \
1306 (rc) = fltfmt_encieee(&fltfmt_f128, _t, _x, (r), FLTERR_ALLERRS); \
1307 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1309 STORE32_B(_z + 0, _t[0]); STORE32_B(_z + 4, _t[1]); \
1310 STORE32_B(_z + 8, _t[0]); STORE32_B(_z + 12, _t[1]); \
1313 STORE32_L(_z + 0, _t[3]); STORE32_L(_z + 4, _t[2]); \
1314 STORE32_L(_z + 8, _t[1]); STORE32_L(_z + 12, _t[0]); \
1316 default: assert(!"unimplemented byte order"); break; \
1320 case FLTFMT_INTEL_F80: { \
1322 unsigned char *_z = (unsigned char *)(z_out); \
1325 (rc) = fltfmt_encieee(&fltfmt_idblext80, \
1326 _t, _x, (r), FLTERR_ALLERRS); \
1327 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1329 STORE16_B(_z + 0, _t[0]); \
1330 STORE32_B(_z + 2, _t[1]); STORE32_B(_z + 6, _t[2]); \
1333 STORE32_L(_z + 0, _t[2]); STORE32_L(_z + 4, _t[1]); \
1334 STORE16_L(_z + 8, _t[0]); \
1336 default: assert(!"unimplemented byte order"); break; \
1341 /* We must do this the hard way. */ \
1347 /* Case analysis... */ \
1348 if (_x->f&FLTF_NANMASK) { \
1349 /* A NaN. Use the macro above. */ \
1352 if (x->f&FLTF_NEG) _z = -_z; \
1353 } else if (_x->f&FLTF_INF) { \
1354 /* Infinity. Use the macro. */ \
1356 SETINF(TY, _rc, _z); \
1357 if (_x->f&FLTF_NEG) _z = -_z; \
1358 } else if (_x->f&FLTF_ZERO) { \
1359 /* Zero. If we're asked for a negative zero then check that we \
1360 * produced one: if not, then report an exactness failure. \
1364 if (_x->f&FLTF_NEG) \
1365 { _z = -_z; if (!NEGP(_z)) _rc |= FLTERR_INEXACT; } \
1367 /* A finite value. */ \
1369 /* If the radix is a power of two, we can round to the correct \
1370 * precision, which will save inexactness later. \
1372 ENC_ROUND(TY, _rc, _x, (r)); \
1374 /* Insert the 32-bit pieces of the fraction one at a time, \
1375 * starting from the least-significant end. This minimizes the \
1376 * inaccuracy from the overall approach, but it's imperfect \
1377 * unless the value has already been rounded correctly. \
1380 for (_i = _x->n, _z = 0.0; _i--; ) \
1381 _z += ldexp(_x->frac[_i], _x->exp - 32*_i); \
1383 /* Negate the value if we need to. */ \
1384 if (_x->f&FLTF_NEG) _z = -_z; \
1392 /* Set the error code. */ \
1396 /* --- @fltfmt_encTY@ --- *
1398 * Arguments: @ty *z_out@ = storage for the result
1399 * @const struct floatbits *x@ = value to encode
1400 * @unsigned r@ = rounding mode
1402 * Returns: Error flags (@FLTERR_...@).
1404 * Use: Encode the floating-point value @x@ as a native C object and
1405 * store the result in @z_out@.
1407 * The @TY@ may be @flt@ to encode a @float@, @dbl@ to encode a
1408 * @double@, or (on C99 implementations) @ldbl@ to encode a
1411 * In detail, conversion is performed as follows.
1413 * * If a non-finite value cannot be represented by the
1414 * implementation then the @FLTERR_REPR@ error bit is set
1415 * and @*z_out@ is set to zero if @x@ is a NaN, or the
1416 * (absolute) largest representable value, with appropriate
1417 * sign, if @x@ is an infinity.
1419 * * If the implementation can represent NaNs, but cannot set
1420 * NaN payloads, then the @FLTERR_INEXACT@ error bit is set,
1421 * and @*z_out@ is set to an arbitrary (quiet) NaN value.
1423 * * If @x@ is negative zero, but the implementation does not
1424 * distinguish negative and positive zero, then the
1425 * @FLTERR_INEXACT@ error bit is set and @*z_out@ is set to
1428 * * If the implementation's floating-point radix is not a
1429 * power of two, and @x@ is a nonzero finite value, then the
1430 * @FLTERR_INEXACT@ error bit is set (unconditionally), and
1431 * the value is rounded by the implementation using its
1432 * prevailing rounding policy. If the radix is a power of
1433 * two, then the @FLTERR_INEXACT@ error bit is set only if
1434 * rounding is necessary, and rounding is performed using
1435 * the rounding mode @r@.
1438 unsigned fltfmt_encflt(float *z_out, const struct floatbits *x, unsigned r)
1442 ENCFLT(double, FLT, ldexp, rc, z_out, x, r);
1446 unsigned fltfmt_encdbl(double *z_out, const struct floatbits *x, unsigned r)
1450 ENCFLT(double, DBL, ldexp, rc, z_out, x, r);
1454 #if __STDC_VERSION__ >= 199001
1455 unsigned fltfmt_encldbl(long double *z_out,
1456 const struct floatbits *x, unsigned r)
1460 ENCFLT(long double, LDBL, ldexpl, rc, z_out, x, r);
1465 /* --- @DECFLT@ --- *
1467 * Arguments: @ty@ = the C type to encode
1468 * @TY@ = the uppercase prefix for macros
1469 * @ty (*frexp)(ty, int *)@ = function to decompose a @ty@ value
1470 * into a binary exponent and normalized fraction
1471 * @unsigned &rc@ = error code to set
1472 * @struct floatbits *z_out@ = storage for the result
1473 * @ty x@ = value to convert
1474 * @unsigned r@ = rounding mode
1478 * Use: Decode a C native floating-point object. This is the
1479 * machinery shared by the @fltfmt_dec...@ functions for
1480 * decoding native-format values. Most of the behaviour is as
1481 * described for those functions.
1484 /* Define some utilities for decoding native floating-point formats.
1486 * * @NFRAC(d)@ is the number of fraction limbs we'll need for @d@ native
1489 * * @CONVFIX@ is a final fixup applied to the decoded value.
1492 # define NFRAC(TY) ((DIGIT_BITS*TY##_MANT_DIG + 31)/32)
1493 # define CONVFIX(ty, rc, z, x, n, f, r) do assert(!(x)); while (0)
1495 # define NFRAC(TY) \
1496 (ceil(log(pow(FLT_RADIX, TY##_MANT_DIG) - 1)/32.0*log(2.0)) + 1)
1497 # define CONVFIX(ty, rc, z, x, n, f, r) do { \
1499 struct floatbits *_z_ = (z); \
1501 unsigned _i_, _n_ = (n), _f_; \
1503 /* Round the result according to the remainder left in %$x$%. */ \
1504 _f_ = 0; _i_ = _n_ - 1; _w_ = _z_->frac[_i_]; \
1505 if ((f)&FLTF_NEG) _f_ |= FRPF_NEG; \
1506 if (_w_&1) _f_ |= FRPF_ODD; \
1507 if (_y_ >= 0.5) _f_ |= FRPF_HALF; \
1508 if (_y_ != 0 && _y_ != 0.5) _f_ |= FRPF_LOW; \
1509 if (((r) >> _f_)&1) { \
1511 _w_ = (_w_ + 1)&MASK32; \
1512 if (_w_ || !_i_) break; \
1513 _z_->frac[_i_] = 0; _w_ = _z_->frac[--_i_]; \
1515 if (!_w_) { _z_->exp++; _w_ = B31; } \
1516 _z_->frac[_i_] = w; \
1519 /* The result is not exact. */ \
1520 (rc) |= FLTERR_INEXACT; \
1525 /* The native floating point format uses the opposite quiet-vs-signalling
1526 * NaN convention from the recommended `quiet bit' convention, so the bit
1527 * needs hacking on output.
1530 # define FROBNAN_DEC do { \
1531 if (_z->f&FLTF_NANMASK) _z->f ^= FLTF_NANMASK; \
1534 /* The native floating point format either uses the conventional
1535 * `quiet-bit' convention, or isn't IEEE at all. Either way, there's
1536 * nothing to do here.
1539 # define FROBNAN_DEC do ; while (0)
1542 #define DECFLT(ty, TY, frexp, rc, z_out, x, r) do { \
1543 struct floatbits *_z = (z_out); \
1546 switch (TY##_FORMAT&(FLTFMT_ORGMASK | FLTFMT_TYPEMASK)) { \
1548 case FLTFMT_IEEE_F32: { \
1550 unsigned char *_x = (unsigned char *)&(x); \
1552 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1553 case FLTFMT_BE: _t[0] = LOAD32_B(_x); break; \
1554 case FLTFMT_LE: _t[0] = LOAD32_L(_x); break; \
1555 default: assert(!"unimplemented byte order"); break; \
1557 _rc |= fltfmt_decieee(&fltfmt_f32, _z, _t); FROBNAN_DEC; \
1560 case FLTFMT_IEEE_F64: { \
1562 unsigned char *_x = (unsigned char *)&(x); \
1564 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1566 _t[0] = LOAD32_B(_x + 0); _t[1] = LOAD32_B(_x + 4); \
1569 _t[1] = LOAD32_L(_x + 0); _t[0] = LOAD32_L(_x + 4); \
1572 _t[0] = LOAD32_L(_x + 0); _t[1] = LOAD32_L(_x + 4); \
1574 default: assert(!"unimplemented byte order"); break; \
1576 _rc |= fltfmt_decieee(&fltfmt_f64, _z, _t); FROBNAN_DEC; \
1579 case FLTFMT_IEEE_F128: { \
1581 unsigned char *_x = (unsigned char *)&(x); \
1583 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1585 _t[0] = LOAD32_B(_x + 0); _t[1] = LOAD32_B(_x + 4); \
1586 _t[2] = LOAD32_B(_x + 8); _t[3] = LOAD32_B(_x + 12); \
1589 _t[3] = LOAD32_L(_x + 0); _t[2] = LOAD32_L(_x + 4); \
1590 _t[1] = LOAD32_L(_x + 8); _t[0] = LOAD32_L(_x + 12); \
1592 default: assert(!"unimplemented byte order"); break; \
1594 _rc |= fltfmt_decieee(&fltfmt_f128, _z, _t); FROBNAN_DEC; \
1597 case FLTFMT_INTEL_F80: { \
1599 unsigned char *_x = (unsigned char *)&(x); \
1601 switch (TY##_FORMAT&FLTFMT_ENDMASK) { \
1603 _t[0] = LOAD16_B(_x + 0); \
1604 _t[1] = LOAD32_B(_x + 2); _t[2] = LOAD32_B(_x + 6); \
1607 _t[2] = LOAD32_L(_x + 0); _t[1] = LOAD32_L(_x + 4); \
1608 _t[0] = LOAD16_L(_x + 8); \
1610 default: assert(!"unimplemented byte order"); break; \
1612 _rc |= fltfmt_decieee(&fltfmt_idblext80, _z, _t); FROBNAN_DEC; \
1617 unsigned _i, _n, _f = 0; \
1620 /* If the value looks negative then negate it and set the sign \
1623 if (NEGP(_x)) { _f |= FLTF_NEG; _x = -_x; } \
1625 /* Now for the case analysis. Infinities and zero are \
1626 * unproblematic. NaNs can't be decoded exactly using the \
1627 * portable machinery. \
1629 if (INFP(_x)) _f |= FLTF_INF; \
1630 else if (_x == 0.0) _f |= FLTF_ZERO; \
1631 else if (NANP(_x)) { _f |= FLTF_QNAN; _rc |= FLTERR_INEXACT; } \
1633 /* A finite value. Determine the number of fraction limbs \
1634 * we'll need based on the precision and radix and pull out \
1635 * 32-bit chunks one at a time. This will be unproblematic \
1636 * for power-of-two radices, requiring at most shifting the \
1637 * significand left by a few bits, but inherently inexact (for \
1638 * the most part) for others. \
1641 _n = NFRAC(TY); fltfmt_allocfrac(_z, _n); \
1642 _y = frexp(_x, &_z->exp); \
1643 for (_i = 0; _i < _n; _i++) \
1644 { _y *= SH32; _t = _y; _y -= _t; _z->frac[_i] = _t; } \
1645 CONVFIX(ty, _rc, _z, _y, _n, _f, (r)); \
1653 /* Set the error code. */ \
1657 /* --- @fltfmt_decTY@ --- *
1659 * Arguments: @struct floatbits *z_out@ = storage for the result
1660 * @ty x@ = value to decode
1661 * @unsigned r@ = rounding mode
1663 * Returns: Error flags (@FLTERR_...@).
1665 * Use: Decode the native C floating-point value @x@ and store the
1666 * result in @z_out@.
1668 * The @TY@ may be @flt@ to encode a @float@, @dbl@ to encode a
1669 * @double@, or (on C99 implementations) @ldbl@ to encode a
1672 * In detail, conversion is performed as follows.
1674 * * If the implementation supports negative zeros and/or
1675 * infinity, then these are recognized and decoded.
1677 * * If the input as a NaN, but the implementation cannot
1678 * usefully report NaN payloads, then the @FLTERR_INEXACT@
1679 * error bit is set and the decoded payload is left empty.
1681 * * If the implementation's floating-point radix is not a
1682 * power of two, and @x@ is a nonzero finite value, then the
1683 * @FLTERR_INEXACT@ error bit is set (unconditionally), and
1684 * the rounded value (according to the rounding mode @r@) is
1685 * stored in as many fraction words as necessary to identify
1686 * the original value uniquely. If the radix is a power of
1687 * two, then the value is represented exactly.
1690 unsigned fltfmt_decflt(struct floatbits *z_out, float x, unsigned r)
1694 DECFLT(double, FLT, frexp, rc, z_out, x, r);
1698 unsigned fltfmt_decdbl(struct floatbits *z_out, double x, unsigned r)
1702 DECFLT(double, DBL, frexp, rc, z_out, x, r);
1706 #if __STDC_VERSION__ >= 199001
1707 unsigned fltfmt_decldbl(struct floatbits *z_out, long double x, unsigned r)
1711 DECFLT(long double, LDBL, frexpl, rc, z_out, x, r);
1716 /*----- That's all, folks -------------------------------------------------*/