OSDN Git Service

* Make-lang.in (java/jcf-dump.o): Depend on zipfile.h.
[pf3gnuchains/gcc-fork.git] / libdecnumber / dpd / decimal32.c
1 /* Decimal 32-bit format module for the decNumber C Library.
2    Copyright (C) 2005, 2007 Free Software Foundation, Inc.
3    Contributed by IBM Corporation.  Author Mike Cowlishaw.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 2, or (at your option) any later
10    version.
11
12    In addition to the permissions in the GNU General Public License,
13    the Free Software Foundation gives you unlimited permission to link
14    the compiled version of this file into combinations with other
15    programs, and to distribute those combinations without any
16    restriction coming from the use of this file.  (The General Public
17    License restrictions do apply in other respects; for example, they
18    cover modification of the file, and distribution when not linked
19    into a combine executable.)
20
21    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22    WARRANTY; without even the implied warranty of MERCHANTABILITY or
23    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
24    for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with GCC; see the file COPYING.  If not, write to the Free
28    Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29    02110-1301, USA.  */
30
31 /* ------------------------------------------------------------------ */
32 /* Decimal 32-bit format module                                       */
33 /* ------------------------------------------------------------------ */
34 /* This module comprises the routines for decimal32 format numbers.   */
35 /* Conversions are supplied to and from decNumber and String.         */
36 /*                                                                    */
37 /* This is used when decNumber provides operations, either for all    */
38 /* operations or as a proxy between decNumber and decSingle.          */
39 /*                                                                    */
40 /* Error handling is the same as decNumber (qv.).                     */
41 /* ------------------------------------------------------------------ */
42 #include <string.h>           /* [for memset/memcpy] */
43 #include <stdio.h>            /* [for printf] */
44
45 #include "config.h"           /* GCC definitions */
46 #define  DECNUMDIGITS  7      /* make decNumbers with space for 7 */
47 #include "decNumber.h"        /* base number library */
48 #include "decNumberLocal.h"   /* decNumber local types, etc. */
49 #include "decimal32.h"        /* our primary include */
50
51 /* Utility tables and routines [in decimal64.c] */
52 /* DPD2BIN and the reverse are renamed to prevent link-time conflict */
53 /* if decQuad is also built in the same executable */
54 #define DPD2BIN DPD2BINx
55 #define BIN2DPD BIN2DPDx
56 extern const uInt   COMBEXP[32], COMBMSD[32];
57 extern const uShort DPD2BIN[1024];
58 extern const uShort BIN2DPD[1000];
59 extern const uByte  BIN2CHAR[4001];
60
61 extern void decDigitsToDPD(const decNumber *, uInt *, Int);
62 extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
63
64 #if DECTRACE || DECCHECK
65 void decimal32Show(const decimal32 *);            /* for debug */
66 extern void decNumberShow(const decNumber *);     /* .. */
67 #endif
68
69 /* Useful macro */
70 /* Clear a structure (e.g., a decNumber) */
71 #define DEC_clear(d) memset(d, 0, sizeof(*d))
72
73 /* ------------------------------------------------------------------ */
74 /* decimal32FromNumber -- convert decNumber to decimal32              */
75 /*                                                                    */
76 /*   ds is the target decimal32                                       */
77 /*   dn is the source number (assumed valid)                          */
78 /*   set is the context, used only for reporting errors               */
79 /*                                                                    */
80 /* The set argument is used only for status reporting and for the     */
81 /* rounding mode (used if the coefficient is more than DECIMAL32_Pmax */
82 /* digits or an overflow is detected).  If the exponent is out of the */
83 /* valid range then Overflow or Underflow will be raised.             */
84 /* After Underflow a subnormal result is possible.                    */
85 /*                                                                    */
86 /* DEC_Clamped is set if the number has to be 'folded down' to fit,   */
87 /* by reducing its exponent and multiplying the coefficient by a      */
88 /* power of ten, or if the exponent on a zero had to be clamped.      */
89 /* ------------------------------------------------------------------ */
90 decimal32 * decimal32FromNumber(decimal32 *d32, const decNumber *dn,
91                               decContext *set) {
92   uInt status=0;                   /* status accumulator */
93   Int ae;                          /* adjusted exponent */
94   decNumber  dw;                   /* work */
95   decContext dc;                   /* .. */
96   uInt *pu;                        /* .. */
97   uInt comb, exp;                  /* .. */
98   uInt targ=0;                     /* target 32-bit */
99
100   /* If the number has too many digits, or the exponent could be */
101   /* out of range then reduce the number under the appropriate */
102   /* constraints.  This could push the number to Infinity or zero, */
103   /* so this check and rounding must be done before generating the */
104   /* decimal32] */
105   ae=dn->exponent+dn->digits-1;              /* [0 if special] */
106   if (dn->digits>DECIMAL32_Pmax              /* too many digits */
107    || ae>DECIMAL32_Emax                      /* likely overflow */
108    || ae<DECIMAL32_Emin) {                   /* likely underflow */
109     decContextDefault(&dc, DEC_INIT_DECIMAL32); /* [no traps] */
110     dc.round=set->round;                     /* use supplied rounding */
111     decNumberPlus(&dw, dn, &dc);             /* (round and check) */
112     /* [this changes -0 to 0, so enforce the sign...] */
113     dw.bits|=dn->bits&DECNEG;
114     status=dc.status;                        /* save status */
115     dn=&dw;                                  /* use the work number */
116     } /* maybe out of range */
117
118   if (dn->bits&DECSPECIAL) {                      /* a special value */
119     if (dn->bits&DECINF) targ=DECIMAL_Inf<<24;
120      else {                                       /* sNaN or qNaN */
121       if ((*dn->lsu!=0 || dn->digits>1)           /* non-zero coefficient */
122        && (dn->digits<DECIMAL32_Pmax)) {          /* coefficient fits */
123         decDigitsToDPD(dn, &targ, 0);
124         }
125       if (dn->bits&DECNAN) targ|=DECIMAL_NaN<<24;
126        else targ|=DECIMAL_sNaN<<24;
127       } /* a NaN */
128     } /* special */
129
130    else { /* is finite */
131     if (decNumberIsZero(dn)) {               /* is a zero */
132       /* set and clamp exponent */
133       if (dn->exponent<-DECIMAL32_Bias) {
134         exp=0;                               /* low clamp */
135         status|=DEC_Clamped;
136         }
137        else {
138         exp=dn->exponent+DECIMAL32_Bias;     /* bias exponent */
139         if (exp>DECIMAL32_Ehigh) {           /* top clamp */
140           exp=DECIMAL32_Ehigh;
141           status|=DEC_Clamped;
142           }
143         }
144       comb=(exp>>3) & 0x18;             /* msd=0, exp top 2 bits .. */
145       }
146      else {                             /* non-zero finite number */
147       uInt msd;                         /* work */
148       Int pad=0;                        /* coefficient pad digits */
149
150       /* the dn is known to fit, but it may need to be padded */
151       exp=(uInt)(dn->exponent+DECIMAL32_Bias);    /* bias exponent */
152       if (exp>DECIMAL32_Ehigh) {                  /* fold-down case */
153         pad=exp-DECIMAL32_Ehigh;
154         exp=DECIMAL32_Ehigh;                      /* [to maximum] */
155         status|=DEC_Clamped;
156         }
157
158       /* fastpath common case */
159       if (DECDPUN==3 && pad==0) {
160         targ=BIN2DPD[dn->lsu[0]];
161         if (dn->digits>3) targ|=(uInt)(BIN2DPD[dn->lsu[1]])<<10;
162         msd=(dn->digits==7 ? dn->lsu[2] : 0);
163         }
164        else { /* general case */
165         decDigitsToDPD(dn, &targ, pad);
166         /* save and clear the top digit */
167         msd=targ>>20;
168         targ&=0x000fffff;
169         }
170
171       /* create the combination field */
172       if (msd>=8) comb=0x18 | ((exp>>5) & 0x06) | (msd & 0x01);
173              else comb=((exp>>3) & 0x18) | msd;
174       }
175     targ|=comb<<26;                /* add combination field .. */
176     targ|=(exp&0x3f)<<20;          /* .. and exponent continuation */
177     } /* finite */
178
179   if (dn->bits&DECNEG) targ|=0x80000000;  /* add sign bit */
180
181   /* now write to storage; this is endian */
182   pu=(uInt *)d32->bytes;           /* overlay */
183   *pu=targ;                        /* directly store the int */
184
185   if (status!=0) decContextSetStatus(set, status); /* pass on status */
186   /* decimal32Show(d32); */
187   return d32;
188   } /* decimal32FromNumber */
189
190 /* ------------------------------------------------------------------ */
191 /* decimal32ToNumber -- convert decimal32 to decNumber                */
192 /*   d32 is the source decimal32                                      */
193 /*   dn is the target number, with appropriate space                  */
194 /* No error is possible.                                              */
195 /* ------------------------------------------------------------------ */
196 decNumber * decimal32ToNumber(const decimal32 *d32, decNumber *dn) {
197   uInt msd;                        /* coefficient MSD */
198   uInt exp;                        /* exponent top two bits */
199   uInt comb;                       /* combination field */
200   uInt sour;                       /* source 32-bit */
201   const uInt *pu;                  /* work */
202
203   /* load source from storage; this is endian */
204   pu=(const uInt *)d32->bytes;     /* overlay */
205   sour=*pu;                        /* directly load the int */
206
207   comb=(sour>>26)&0x1f;            /* combination field */
208
209   decNumberZero(dn);               /* clean number */
210   if (sour&0x80000000) dn->bits=DECNEG; /* set sign if negative */
211
212   msd=COMBMSD[comb];               /* decode the combination field */
213   exp=COMBEXP[comb];               /* .. */
214
215   if (exp==3) {                    /* is a special */
216     if (msd==0) {
217       dn->bits|=DECINF;
218       return dn;                   /* no coefficient needed */
219       }
220     else if (sour&0x02000000) dn->bits|=DECSNAN;
221     else dn->bits|=DECNAN;
222     msd=0;                         /* no top digit */
223     }
224    else {                          /* is a finite number */
225     dn->exponent=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; /* unbiased */
226     }
227
228   /* get the coefficient */
229   sour&=0x000fffff;                /* clean coefficient continuation */
230   if (msd) {                       /* non-zero msd */
231     sour|=msd<<20;                 /* prefix to coefficient */
232     decDigitsFromDPD(dn, &sour, 3); /* process 3 declets */
233     return dn;
234     }
235   /* msd=0 */
236   if (!sour) return dn;            /* easy: coefficient is 0 */
237   if (sour&0x000ffc00)             /* need 2 declets? */
238     decDigitsFromDPD(dn, &sour, 2); /* process 2 declets */
239    else
240     decDigitsFromDPD(dn, &sour, 1); /* process 1 declet */
241   return dn;
242   } /* decimal32ToNumber */
243
244 /* ------------------------------------------------------------------ */
245 /* to-scientific-string -- conversion to numeric string               */
246 /* to-engineering-string -- conversion to numeric string              */
247 /*                                                                    */
248 /*   decimal32ToString(d32, string);                                  */
249 /*   decimal32ToEngString(d32, string);                               */
250 /*                                                                    */
251 /*  d32 is the decimal32 format number to convert                     */
252 /*  string is the string where the result will be laid out            */
253 /*                                                                    */
254 /*  string must be at least 24 characters                             */
255 /*                                                                    */
256 /*  No error is possible, and no status can be set.                   */
257 /* ------------------------------------------------------------------ */
258 char * decimal32ToEngString(const decimal32 *d32, char *string){
259   decNumber dn;                         /* work */
260   decimal32ToNumber(d32, &dn);
261   decNumberToEngString(&dn, string);
262   return string;
263   } /* decimal32ToEngString */
264
265 char * decimal32ToString(const decimal32 *d32, char *string){
266   uInt msd;                        /* coefficient MSD */
267   Int  exp;                        /* exponent top two bits or full */
268   uInt comb;                       /* combination field */
269   char *cstart;                    /* coefficient start */
270   char *c;                         /* output pointer in string */
271   const uInt *pu;                  /* work */
272   const uByte *u;                  /* .. */
273   char *s, *t;                     /* .. (source, target) */
274   Int  dpd;                        /* .. */
275   Int  pre, e;                     /* .. */
276   uInt sour;                       /* source 32-bit */
277
278   /* load source from storage; this is endian */
279   pu=(const uInt *)d32->bytes;     /* overlay */
280   sour=*pu;                        /* directly load the int */
281
282   c=string;                        /* where result will go */
283   if (((Int)sour)<0) *c++='-';     /* handle sign */
284
285   comb=(sour>>26)&0x1f;            /* combination field */
286   msd=COMBMSD[comb];               /* decode the combination field */
287   exp=COMBEXP[comb];               /* .. */
288
289   if (exp==3) {
290     if (msd==0) {                  /* infinity */
291       strcpy(c,   "Inf");
292       strcpy(c+3, "inity");
293       return string;               /* easy */
294       }
295     if (sour&0x02000000) *c++='s'; /* sNaN */
296     strcpy(c, "NaN");              /* complete word */
297     c+=3;                          /* step past */
298     if ((sour&0x000fffff)==0) return string; /* zero payload */
299     /* otherwise drop through to add integer; set correct exp */
300     exp=0; msd=0;                  /* setup for following code */
301     }
302    else exp=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; /* unbiased */
303
304   /* convert 7 digits of significand to characters */
305   cstart=c;                        /* save start of coefficient */
306   if (msd) *c++='0'+(char)msd;     /* non-zero most significant digit */
307
308   /* Now decode the declets.  After extracting each one, it is */
309   /* decoded to binary and then to a 4-char sequence by table lookup; */
310   /* the 4-chars are a 1-char length (significant digits, except 000 */
311   /* has length 0).  This allows us to left-align the first declet */
312   /* with non-zero content, then remaining ones are full 3-char */
313   /* length.  We use fixed-length memcpys because variable-length */
314   /* causes a subroutine call in GCC.  (These are length 4 for speed */
315   /* and are safe because the array has an extra terminator byte.) */
316   #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];                   \
317                    if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}      \
318                     else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}
319
320   dpd=(sour>>10)&0x3ff;            /* declet 1 */
321   dpd2char;
322   dpd=(sour)&0x3ff;                /* declet 2 */
323   dpd2char;
324
325   if (c==cstart) *c++='0';         /* all zeros -- make 0 */
326
327   if (exp==0) {                    /* integer or NaN case -- easy */
328     *c='\0';                       /* terminate */
329     return string;
330     }
331
332   /* non-0 exponent */
333   e=0;                             /* assume no E */
334   pre=c-cstart+exp;
335   /* [here, pre-exp is the digits count (==1 for zero)] */
336   if (exp>0 || pre<-5) {           /* need exponential form */
337     e=pre-1;                       /* calculate E value */
338     pre=1;                         /* assume one digit before '.' */
339     } /* exponential form */
340
341   /* modify the coefficient, adding 0s, '.', and E+nn as needed */
342   s=c-1;                           /* source (LSD) */
343   if (pre>0) {                     /* ddd.ddd (plain), perhaps with E */
344     char *dotat=cstart+pre;
345     if (dotat<c) {                 /* if embedded dot needed... */
346       t=c;                              /* target */
347       for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
348       *t='.';                           /* insert the dot */
349       c++;                              /* length increased by one */
350       }
351
352     /* finally add the E-part, if needed; it will never be 0, and has */
353     /* a maximum length of 3 digits (E-101 case) */
354     if (e!=0) {
355       *c++='E';                    /* starts with E */
356       *c++='+';                    /* assume positive */
357       if (e<0) {
358         *(c-1)='-';                /* oops, need '-' */
359         e=-e;                      /* uInt, please */
360         }
361       u=&BIN2CHAR[e*4];            /* -> length byte */
362       memcpy(c, u+4-*u, 4);        /* copy fixed 4 characters [is safe] */
363       c+=*u;                       /* bump pointer appropriately */
364       }
365     *c='\0';                       /* add terminator */
366     /*printf("res %s\n", string); */
367     return string;
368     } /* pre>0 */
369
370   /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
371   t=c+1-pre;
372   *(t+1)='\0';                          /* can add terminator now */
373   for (; s>=cstart; s--, t--) *t=*s;    /* shift whole coefficient right */
374   c=cstart;
375   *c++='0';                             /* always starts with 0. */
376   *c++='.';
377   for (; pre<0; pre++) *c++='0';        /* add any 0's after '.' */
378   /*printf("res %s\n", string); */
379   return string;
380   } /* decimal32ToString */
381
382 /* ------------------------------------------------------------------ */
383 /* to-number -- conversion from numeric string                        */
384 /*                                                                    */
385 /*   decimal32FromString(result, string, set);                        */
386 /*                                                                    */
387 /*  result  is the decimal32 format number which gets the result of   */
388 /*          the conversion                                            */
389 /*  *string is the character string which should contain a valid      */
390 /*          number (which may be a special value)                     */
391 /*  set     is the context                                            */
392 /*                                                                    */
393 /* The context is supplied to this routine is used for error handling */
394 /* (setting of status and traps) and for the rounding mode, only.     */
395 /* If an error occurs, the result will be a valid decimal32 NaN.      */
396 /* ------------------------------------------------------------------ */
397 decimal32 * decimal32FromString(decimal32 *result, const char *string,
398                                 decContext *set) {
399   decContext dc;                             /* work */
400   decNumber dn;                              /* .. */
401
402   decContextDefault(&dc, DEC_INIT_DECIMAL32); /* no traps, please */
403   dc.round=set->round;                        /* use supplied rounding */
404
405   decNumberFromString(&dn, string, &dc);     /* will round if needed */
406   decimal32FromNumber(result, &dn, &dc);
407   if (dc.status!=0) {                        /* something happened */
408     decContextSetStatus(set, dc.status);     /* .. pass it on */
409     }
410   return result;
411   } /* decimal32FromString */
412
413 /* ------------------------------------------------------------------ */
414 /* decimal32IsCanonical -- test whether encoding is canonical         */
415 /*   d32 is the source decimal32                                      */
416 /*   returns 1 if the encoding of d32 is canonical, 0 otherwise       */
417 /* No error is possible.                                              */
418 /* ------------------------------------------------------------------ */
419 uint32_t decimal32IsCanonical(const decimal32 *d32) {
420   decNumber dn;                         /* work */
421   decimal32 canon;                      /* .. */
422   decContext dc;                        /* .. */
423   decContextDefault(&dc, DEC_INIT_DECIMAL32);
424   decimal32ToNumber(d32, &dn);
425   decimal32FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
426   return memcmp(d32, &canon, DECIMAL32_Bytes)==0;
427   } /* decimal32IsCanonical */
428
429 /* ------------------------------------------------------------------ */
430 /* decimal32Canonical -- copy an encoding, ensuring it is canonical   */
431 /*   d32 is the source decimal32                                      */
432 /*   result is the target (may be the same decimal32)                 */
433 /*   returns result                                                   */
434 /* No error is possible.                                              */
435 /* ------------------------------------------------------------------ */
436 decimal32 * decimal32Canonical(decimal32 *result, const decimal32 *d32) {
437   decNumber dn;                         /* work */
438   decContext dc;                        /* .. */
439   decContextDefault(&dc, DEC_INIT_DECIMAL32);
440   decimal32ToNumber(d32, &dn);
441   decimal32FromNumber(result, &dn, &dc);/* result will now be canonical */
442   return result;
443   } /* decimal32Canonical */
444
445 #if DECTRACE || DECCHECK
446 /* Macros for accessing decimal32 fields.  These assume the argument
447    is a reference (pointer) to the decimal32 structure, and the
448    decimal32 is in network byte order (big-endian) */
449 /* Get sign */
450 #define decimal32Sign(d)       ((unsigned)(d)->bytes[0]>>7)
451
452 /* Get combination field */
453 #define decimal32Comb(d)       (((d)->bytes[0] & 0x7c)>>2)
454
455 /* Get exponent continuation [does not remove bias] */
456 #define decimal32ExpCon(d)     ((((d)->bytes[0] & 0x03)<<4)           \
457                              | ((unsigned)(d)->bytes[1]>>4))
458
459 /* Set sign [this assumes sign previously 0] */
460 #define decimal32SetSign(d, b) {                                      \
461   (d)->bytes[0]|=((unsigned)(b)<<7);}
462
463 /* Set exponent continuation [does not apply bias] */
464 /* This assumes range has been checked and exponent previously 0; */
465 /* type of exponent must be unsigned */
466 #define decimal32SetExpCon(d, e) {                                    \
467   (d)->bytes[0]|=(uint8_t)((e)>>4);                                   \
468   (d)->bytes[1]|=(uint8_t)(((e)&0x0F)<<4);}
469
470 /* ------------------------------------------------------------------ */
471 /* decimal32Show -- display a decimal32 in hexadecimal [debug aid]    */
472 /*   d32 -- the number to show                                        */
473 /* ------------------------------------------------------------------ */
474 /* Also shows sign/cob/expconfields extracted - valid bigendian only */
475 void decimal32Show(const decimal32 *d32) {
476   char buf[DECIMAL32_Bytes*2+1];
477   Int i, j=0;
478
479   if (DECLITEND) {
480     for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
481       sprintf(&buf[j], "%02x", d32->bytes[3-i]);
482       }
483     printf(" D32> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
484            d32->bytes[3]>>7, (d32->bytes[3]>>2)&0x1f,
485            ((d32->bytes[3]&0x3)<<4)| (d32->bytes[2]>>4));
486     }
487    else {
488     for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
489       sprintf(&buf[j], "%02x", d32->bytes[i]);
490       }
491     printf(" D32> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
492            decimal32Sign(d32), decimal32Comb(d32), decimal32ExpCon(d32));
493     }
494   } /* decimal32Show */
495 #endif