xref: /csrg-svn/lib/libc/quad/fixunsdfdi.c (revision 61160)
153437Sbostic /*-
2*61160Sbostic  * Copyright (c) 1992, 1993
3*61160Sbostic  *	The Regents of the University of California.  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*61160Sbostic static char sccsid[] = "@(#)fixunsdfdi.c	8.1 (Berkeley) 06/04/93";
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  */
2754431Sbostic u_quad_t
__fixunsdfdi(x)2854431Sbostic __fixunsdfdi(x)
2954431Sbostic 	double x;
3053437Sbostic {
3153794Sbostic 	double toppart;
3253794Sbostic 	union uu t;
3353437Sbostic 
3453794Sbostic 	if (x < 0)
3553794Sbostic 		return (UQUAD_MAX);	/* ??? should be 0?  ERANGE??? */
3655180Storek #ifdef notdef				/* this falls afoul of a GCC bug */
3753794Sbostic 	if (x >= UQUAD_MAX)
3853794Sbostic 		return (UQUAD_MAX);
3955180Storek #else					/* so we wire in 2^64-1 instead */
4055180Storek 	if (x >= 18446744073709551615.0)
4155180Storek 		return (UQUAD_MAX);
4255180Storek #endif
4353794Sbostic 	/*
4453794Sbostic 	 * Get the upper part of the result.  Note that the divide
4553794Sbostic 	 * may round up; we want to avoid this if possible, so we
4653794Sbostic 	 * subtract `1/2' first.
4753794Sbostic 	 */
4853794Sbostic 	toppart = (x - ONE_HALF) / ONE;
4953794Sbostic 	/*
5054431Sbostic 	 * Now build a u_quad_t out of the top part.  The difference
5153794Sbostic 	 * between x and this is the bottom part (this may introduce
5253794Sbostic 	 * a few fuzzy bits, but what the heck).  With any luck this
5353794Sbostic 	 * difference will be nonnegative: x should wind up in the
5453794Sbostic 	 * range [0..ULONG_MAX].  For paranoia, we assume [LONG_MIN..
5553794Sbostic 	 * 2*ULONG_MAX] instead.
5653794Sbostic 	 */
5753794Sbostic 	t.ul[H] = (unsigned long)toppart;
5853794Sbostic 	t.ul[L] = 0;
5953794Sbostic 	x -= (double)t.uq;
6053794Sbostic 	if (x < 0) {
6153794Sbostic 		t.ul[H]--;
6253794Sbostic 		x += ULONG_MAX;
6353794Sbostic 	}
6453794Sbostic 	if (x > ULONG_MAX) {
6553794Sbostic 		t.ul[H]++;
6653794Sbostic 		x -= ULONG_MAX;
6753794Sbostic 	}
6853794Sbostic 	t.ul[L] = (u_long)x;
6953794Sbostic 	return (t.uq);
7053437Sbostic }
71