xref: /original-bsd/lib/libc/quad/fixunsdfdi.c (revision c3e32dec)
1 /*-
2  * Copyright (c) 1992, 1993
3  *	The Regents of the University of California.  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[] = "@(#)fixunsdfdi.c	8.1 (Berkeley) 06/04/93";
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 double to (unsigned) quad.
24  * Not sure what to do with negative numbers---for now, anything out
25  * of range becomes UQUAD_MAX.
26  */
27 u_quad_t
28 __fixunsdfdi(x)
29 	double x;
30 {
31 	double toppart;
32 	union uu t;
33 
34 	if (x < 0)
35 		return (UQUAD_MAX);	/* ??? should be 0?  ERANGE??? */
36 #ifdef notdef				/* this falls afoul of a GCC bug */
37 	if (x >= UQUAD_MAX)
38 		return (UQUAD_MAX);
39 #else					/* so we wire in 2^64-1 instead */
40 	if (x >= 18446744073709551615.0)
41 		return (UQUAD_MAX);
42 #endif
43 	/*
44 	 * Get the upper part of the result.  Note that the divide
45 	 * may round up; we want to avoid this if possible, so we
46 	 * subtract `1/2' first.
47 	 */
48 	toppart = (x - ONE_HALF) / ONE;
49 	/*
50 	 * Now build a u_quad_t out of the top part.  The difference
51 	 * between x and this is the bottom part (this may introduce
52 	 * a few fuzzy bits, but what the heck).  With any luck this
53 	 * difference will be nonnegative: x should wind up in the
54 	 * range [0..ULONG_MAX].  For paranoia, we assume [LONG_MIN..
55 	 * 2*ULONG_MAX] instead.
56 	 */
57 	t.ul[H] = (unsigned long)toppart;
58 	t.ul[L] = 0;
59 	x -= (double)t.uq;
60 	if (x < 0) {
61 		t.ul[H]--;
62 		x += ULONG_MAX;
63 	}
64 	if (x > ULONG_MAX) {
65 		t.ul[H]++;
66 		x -= ULONG_MAX;
67 	}
68 	t.ul[L] = (u_long)x;
69 	return (t.uq);
70 }
71