xref: /csrg-svn/lib/libc/quad/fixunssfdi.c (revision 54746)
1 /*-
2  * Copyright (c) 1992 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This software was developed by the Computer Systems Engineering group
6  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
7  * contributed to Berkeley.
8  *
9  * %sccs.include.redist.c%
10  */
11 
12 #if defined(LIBC_SCCS) && !defined(lint)
13 static char sccsid[] = "@(#)fixunssfdi.c	5.1 (Berkeley) 07/07/92";
14 #endif /* LIBC_SCCS and not lint */
15 
16 #include "quad.h"
17 
18 #define	ONE_FOURTH	(1 << (LONG_BITS - 2))
19 #define	ONE_HALF	(ONE_FOURTH * 2.0)
20 #define	ONE		(ONE_FOURTH * 4.0)
21 
22 /*
23  * Convert float to (unsigned) quad.  We do most of our work in double,
24  * out of sheer paranoia.
25  *
26  * Not sure what to do with negative numbers---for now, anything out
27  * of range becomes UQUAD_MAX.
28  *
29  * N.B.: must use new ANSI syntax (sorry).
30  */
31 u_quad_t
32 __fixunssfdi(float f)
33 {
34 	double x, toppart;
35 	union uu t;
36 
37 	if (f < 0)
38 		return (UQUAD_MAX);	/* ??? should be 0?  ERANGE??? */
39 	if (f >= UQUAD_MAX)
40 		return (UQUAD_MAX);
41 	x = f;
42 	/*
43 	 * Get the upper part of the result.  Note that the divide
44 	 * may round up; we want to avoid this if possible, so we
45 	 * subtract `1/2' first.
46 	 */
47 	toppart = (x - ONE_HALF) / ONE;
48 	/*
49 	 * Now build a u_quad_t out of the top part.  The difference
50 	 * between x and this is the bottom part (this may introduce
51 	 * a few fuzzy bits, but what the heck).  With any luck this
52 	 * difference will be nonnegative: x should wind up in the
53 	 * range [0..ULONG_MAX].  For paranoia, we assume [LONG_MIN..
54 	 * 2*ULONG_MAX] instead.
55 	 */
56 	t.ul[H] = (unsigned long)toppart;
57 	t.ul[L] = 0;
58 	x -= (double)t.uq;
59 	if (x < 0) {
60 		t.ul[H]--;
61 		x += ULONG_MAX;
62 	}
63 	if (x > ULONG_MAX) {
64 		t.ul[H]++;
65 		x -= ULONG_MAX;
66 	}
67 	t.ul[L] = (u_long)x;
68 	return (t.uq);
69 }
70