xref: /csrg-svn/lib/libc/quad/fixunsdfdi.c (revision 54431)
153437Sbostic /*-
253437Sbostic  * Copyright (c) 1992 The Regents of the University of California.
353437Sbostic  * All rights reserved.
453437Sbostic  *
553794Sbostic  * This software was developed by the Computer Systems Engineering group
653794Sbostic  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
753794Sbostic  * contributed to Berkeley.
853794Sbostic  *
953437Sbostic  * %sccs.include.redist.c%
1053437Sbostic  */
1153437Sbostic 
1253437Sbostic #if defined(LIBC_SCCS) && !defined(lint)
13*54431Sbostic static char sccsid[] = "@(#)fixunsdfdi.c	5.4 (Berkeley) 06/25/92";
1453437Sbostic #endif /* LIBC_SCCS and not lint */
1553437Sbostic 
1653794Sbostic #include "quad.h"
1753459Sbostic 
1853794Sbostic #define	ONE_FOURTH	(1 << (LONG_BITS - 2))
1953794Sbostic #define	ONE_HALF	(ONE_FOURTH * 2.0)
2053794Sbostic #define	ONE		(ONE_FOURTH * 4.0)
2153459Sbostic 
2253794Sbostic /*
2353794Sbostic  * Convert double to (unsigned) quad.
2453794Sbostic  * Not sure what to do with negative numbers---for now, anything out
2553794Sbostic  * of range becomes UQUAD_MAX.
2653794Sbostic  */
27*54431Sbostic u_quad_t
28*54431Sbostic __fixunsdfdi(x)
29*54431Sbostic 	double x;
3053437Sbostic {
3153794Sbostic 	double toppart;
3253794Sbostic 	union uu t;
3353437Sbostic 
3453794Sbostic 	if (x < 0)
3553794Sbostic 		return (UQUAD_MAX);	/* ??? should be 0?  ERANGE??? */
3653794Sbostic 	if (x >= UQUAD_MAX)
3753794Sbostic 		return (UQUAD_MAX);
3853794Sbostic 	/*
3953794Sbostic 	 * Get the upper part of the result.  Note that the divide
4053794Sbostic 	 * may round up; we want to avoid this if possible, so we
4153794Sbostic 	 * subtract `1/2' first.
4253794Sbostic 	 */
4353794Sbostic 	toppart = (x - ONE_HALF) / ONE;
4453794Sbostic 	/*
45*54431Sbostic 	 * Now build a u_quad_t out of the top part.  The difference
4653794Sbostic 	 * between x and this is the bottom part (this may introduce
4753794Sbostic 	 * a few fuzzy bits, but what the heck).  With any luck this
4853794Sbostic 	 * difference will be nonnegative: x should wind up in the
4953794Sbostic 	 * range [0..ULONG_MAX].  For paranoia, we assume [LONG_MIN..
5053794Sbostic 	 * 2*ULONG_MAX] instead.
5153794Sbostic 	 */
5253794Sbostic 	t.ul[H] = (unsigned long)toppart;
5353794Sbostic 	t.ul[L] = 0;
5453794Sbostic 	x -= (double)t.uq;
5553794Sbostic 	if (x < 0) {
5653794Sbostic 		t.ul[H]--;
5753794Sbostic 		x += ULONG_MAX;
5853794Sbostic 	}
5953794Sbostic 	if (x > ULONG_MAX) {
6053794Sbostic 		t.ul[H]++;
6153794Sbostic 		x -= ULONG_MAX;
6253794Sbostic 	}
6353794Sbostic 	t.ul[L] = (u_long)x;
6453794Sbostic 	return (t.uq);
6553437Sbostic }
66