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.4 (Berkeley) 06/25/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 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 if (x >= UQUAD_MAX) 37 return (UQUAD_MAX); 38 /* 39 * Get the upper part of the result. Note that the divide 40 * may round up; we want to avoid this if possible, so we 41 * subtract `1/2' first. 42 */ 43 toppart = (x - ONE_HALF) / ONE; 44 /* 45 * Now build a u_quad_t out of the top part. The difference 46 * between x and this is the bottom part (this may introduce 47 * a few fuzzy bits, but what the heck). With any luck this 48 * difference will be nonnegative: x should wind up in the 49 * range [0..ULONG_MAX]. For paranoia, we assume [LONG_MIN.. 50 * 2*ULONG_MAX] instead. 51 */ 52 t.ul[H] = (unsigned long)toppart; 53 t.ul[L] = 0; 54 x -= (double)t.uq; 55 if (x < 0) { 56 t.ul[H]--; 57 x += ULONG_MAX; 58 } 59 if (x > ULONG_MAX) { 60 t.ul[H]++; 61 x -= ULONG_MAX; 62 } 63 t.ul[L] = (u_long)x; 64 return (t.uq); 65 } 66