xref: /original-bsd/lib/libc/quad/fixunsdfdi.c (revision d84495ef)
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[] = "@(#)fixunsdfdi.c	5.3 (Berkeley) 06/02/92";
14 #endif /* LIBC_SCCS and not lint */
15 
16 #include "quad.h"
17 
18 #ifndef UQUAD_MAX	/* should be in <limits.h> maybe? */
19 #define	UQUAD_MAX ((u_quad)0 - 1)
20 #endif
21 
22 #define	ONE_FOURTH	(1 << (LONG_BITS - 2))
23 #define	ONE_HALF	(ONE_FOURTH * 2.0)
24 #define	ONE		(ONE_FOURTH * 4.0)
25 
26 /*
27  * Convert double to (unsigned) quad.
28  * Not sure what to do with negative numbers---for now, anything out
29  * of range becomes UQUAD_MAX.
30  */
31 u_quad
32 __fixunsdfdi(double x)
33 {
34 	double toppart;
35 	union uu t;
36 
37 	if (x < 0)
38 		return (UQUAD_MAX);	/* ??? should be 0?  ERANGE??? */
39 	if (x >= UQUAD_MAX)
40 		return (UQUAD_MAX);
41 	/*
42 	 * Get the upper part of the result.  Note that the divide
43 	 * may round up; we want to avoid this if possible, so we
44 	 * subtract `1/2' first.
45 	 */
46 	toppart = (x - ONE_HALF) / ONE;
47 	/*
48 	 * Now build a u_quad out of the top part.  The difference
49 	 * between x and this is the bottom part (this may introduce
50 	 * a few fuzzy bits, but what the heck).  With any luck this
51 	 * difference will be nonnegative: x should wind up in the
52 	 * range [0..ULONG_MAX].  For paranoia, we assume [LONG_MIN..
53 	 * 2*ULONG_MAX] instead.
54 	 */
55 	t.ul[H] = (unsigned long)toppart;
56 	t.ul[L] = 0;
57 	x -= (double)t.uq;
58 	if (x < 0) {
59 		t.ul[H]--;
60 		x += ULONG_MAX;
61 	}
62 	if (x > ULONG_MAX) {
63 		t.ul[H]++;
64 		x -= ULONG_MAX;
65 	}
66 	t.ul[L] = (u_long)x;
67 	return (t.uq);
68 }
69