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