xref: /openbmc/qemu/libdecnumber/dpd/decimal64.c (revision b2a3cbb8)
1 /* Decimal 64-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 64-bit format module					      */
33 /* ------------------------------------------------------------------ */
34 /* This module comprises the routines for decimal64 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 "qemu/osdep.h"
43 
44 #include "libdecnumber/dconfig.h"
45 #define	 DECNUMDIGITS 16      /* make decNumbers with space for 16 */
46 #include "libdecnumber/decNumber.h"
47 #include "libdecnumber/decNumberLocal.h"
48 #include "libdecnumber/dpd/decimal64.h"
49 
50 /* Utility routines and tables [in decimal64.c]; externs for C++ */
51 extern const uInt COMBEXP[32], COMBMSD[32];
52 extern const uByte  BIN2CHAR[4001];
53 
54 extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
55 extern void decDigitsToDPD(const decNumber *, uInt *, Int);
56 
57 #if DECTRACE || DECCHECK
58 void decimal64Show(const decimal64 *);		  /* for debug */
59 extern void decNumberShow(const decNumber *);	  /* .. */
60 #endif
61 
62 /* Useful macro */
63 /* Clear a structure (e.g., a decNumber) */
64 #define DEC_clear(d) memset(d, 0, sizeof(*d))
65 
66 /* define and include the tables to use for conversions */
67 #define DEC_BIN2CHAR 1
68 #define DEC_DPD2BIN  1
69 #define DEC_BIN2DPD  1		   /* used for all sizes */
70 #include "libdecnumber/decDPD.h"
71 
72 /* ------------------------------------------------------------------ */
73 /* decimal64FromNumber -- convert decNumber to decimal64	      */
74 /*								      */
75 /*   ds is the target decimal64					      */
76 /*   dn is the source number (assumed valid)			      */
77 /*   set is the context, used only for reporting errors		      */
78 /*								      */
79 /* The set argument is used only for status reporting and for the     */
80 /* rounding mode (used if the coefficient is more than DECIMAL64_Pmax */
81 /* digits or an overflow is detected).	If the exponent is out of the */
82 /* valid range then Overflow or Underflow will be raised.	      */
83 /* After Underflow a subnormal result is possible.		      */
84 /*								      */
85 /* DEC_Clamped is set if the number has to be 'folded down' to fit,   */
86 /* by reducing its exponent and multiplying the coefficient by a      */
87 /* power of ten, or if the exponent on a zero had to be clamped.      */
88 /* ------------------------------------------------------------------ */
decimal64FromNumber(decimal64 * d64,const decNumber * dn,decContext * set)89 decimal64 * decimal64FromNumber(decimal64 *d64, const decNumber *dn,
90 				decContext *set) {
91   uInt status=0;		   /* status accumulator */
92   Int ae;			   /* adjusted exponent */
93   decNumber  dw;		   /* work */
94   decContext dc;		   /* .. */
95   uInt *pu;			   /* .. */
96   uInt comb, exp;		   /* .. */
97   uInt targar[2]={0, 0};	   /* target 64-bit */
98   #define targhi targar[1]	   /* name the word with the sign */
99   #define targlo targar[0]	   /* and the other */
100 
101   /* If the number has too many digits, or the exponent could be */
102   /* out of range then reduce the number under the appropriate */
103   /* constraints.  This could push the number to Infinity or zero, */
104   /* so this check and rounding must be done before generating the */
105   /* decimal64] */
106   ae=dn->exponent+dn->digits-1;		     /* [0 if special] */
107   if (dn->digits>DECIMAL64_Pmax		     /* too many digits */
108    || ae>DECIMAL64_Emax			     /* likely overflow */
109    || ae<DECIMAL64_Emin) {		     /* likely underflow */
110     decContextDefault(&dc, DEC_INIT_DECIMAL64); /* [no traps] */
111     dc.round=set->round;		     /* use supplied rounding */
112     decNumberPlus(&dw, dn, &dc);	     /* (round and check) */
113     /* [this changes -0 to 0, so enforce the sign...] */
114     dw.bits|=dn->bits&DECNEG;
115     status=dc.status;			     /* save status */
116     dn=&dw;				     /* use the work number */
117     } /* maybe out of range */
118 
119   if (dn->bits&DECSPECIAL) {			  /* a special value */
120     if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;
121      else {					  /* sNaN or qNaN */
122       if ((*dn->lsu!=0 || dn->digits>1)		  /* non-zero coefficient */
123        && (dn->digits<DECIMAL64_Pmax)) {	  /* coefficient fits */
124 	decDigitsToDPD(dn, targar, 0);
125 	}
126       if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;
127        else targhi|=DECIMAL_sNaN<<24;
128       } /* a NaN */
129     } /* special */
130 
131    else { /* is finite */
132     if (decNumberIsZero(dn)) {		     /* is a zero */
133       /* set and clamp exponent */
134       if (dn->exponent<-DECIMAL64_Bias) {
135 	exp=0;				     /* low clamp */
136 	status|=DEC_Clamped;
137 	}
138        else {
139 	exp=dn->exponent+DECIMAL64_Bias;     /* bias exponent */
140 	if (exp>DECIMAL64_Ehigh) {	     /* top clamp */
141 	  exp=DECIMAL64_Ehigh;
142 	  status|=DEC_Clamped;
143 	  }
144 	}
145       comb=(exp>>5) & 0x18;		/* msd=0, exp top 2 bits .. */
146       }
147      else {				/* non-zero finite number */
148       uInt msd;				/* work */
149       Int pad=0;			/* coefficient pad digits */
150 
151       /* the dn is known to fit, but it may need to be padded */
152       exp=(uInt)(dn->exponent+DECIMAL64_Bias);	  /* bias exponent */
153       if (exp>DECIMAL64_Ehigh) {		  /* fold-down case */
154 	pad=exp-DECIMAL64_Ehigh;
155 	exp=DECIMAL64_Ehigh;			  /* [to maximum] */
156 	status|=DEC_Clamped;
157 	}
158 
159       /* fastpath common case */
160       if (DECDPUN==3 && pad==0) {
161 	uInt dpd[6]={0,0,0,0,0,0};
162 	uInt i;
163 	Int d=dn->digits;
164 	for (i=0; d>0; i++, d-=3) dpd[i]=BIN2DPD[dn->lsu[i]];
165 	targlo =dpd[0];
166 	targlo|=dpd[1]<<10;
167 	targlo|=dpd[2]<<20;
168 	if (dn->digits>6) {
169 	  targlo|=dpd[3]<<30;
170 	  targhi =dpd[3]>>2;
171 	  targhi|=dpd[4]<<8;
172 	  }
173 	msd=dpd[5];		   /* [did not really need conversion] */
174 	}
175        else { /* general case */
176 	decDigitsToDPD(dn, targar, pad);
177 	/* save and clear the top digit */
178 	msd=targhi>>18;
179 	targhi&=0x0003ffff;
180 	}
181 
182       /* create the combination field */
183       if (msd>=8) comb=0x18 | ((exp>>7) & 0x06) | (msd & 0x01);
184 	     else comb=((exp>>5) & 0x18) | msd;
185       }
186     targhi|=comb<<26;		   /* add combination field .. */
187     targhi|=(exp&0xff)<<18;	   /* .. and exponent continuation */
188     } /* finite */
189 
190   if (dn->bits&DECNEG) targhi|=0x80000000; /* add sign bit */
191 
192   /* now write to storage; this is now always endian */
193   pu=(uInt *)d64->bytes;	   /* overlay */
194   if (DECLITEND) {
195     pu[0]=targar[0];		   /* directly store the low int */
196     pu[1]=targar[1];		   /* then the high int */
197     }
198    else {
199     pu[0]=targar[1];		   /* directly store the high int */
200     pu[1]=targar[0];		   /* then the low int */
201     }
202 
203   if (status!=0) decContextSetStatus(set, status); /* pass on status */
204   /* decimal64Show(d64); */
205   return d64;
206   } /* decimal64FromNumber */
207 
208 /* ------------------------------------------------------------------ */
209 /* decimal64ToNumber -- convert decimal64 to decNumber		      */
210 /*   d64 is the source decimal64				      */
211 /*   dn is the target number, with appropriate space		      */
212 /* No error is possible.					      */
213 /* ------------------------------------------------------------------ */
decimal64ToNumber(const decimal64 * d64,decNumber * dn)214 decNumber * decimal64ToNumber(const decimal64 *d64, decNumber *dn) {
215   uInt msd;			   /* coefficient MSD */
216   uInt exp;			   /* exponent top two bits */
217   uInt comb;			   /* combination field */
218   const uInt *pu;		   /* work */
219   Int  need;			   /* .. */
220   uInt sourar[2];		   /* source 64-bit */
221   #define sourhi sourar[1]	   /* name the word with the sign */
222   #define sourlo sourar[0]	   /* and the lower word */
223 
224   /* load source from storage; this is endian */
225   pu=(const uInt *)d64->bytes;	   /* overlay */
226   if (DECLITEND) {
227     sourlo=pu[0];		   /* directly load the low int */
228     sourhi=pu[1];		   /* then the high int */
229     }
230    else {
231     sourhi=pu[0];		   /* directly load the high int */
232     sourlo=pu[1];		   /* then the low int */
233     }
234 
235   comb=(sourhi>>26)&0x1f;	   /* combination field */
236 
237   decNumberZero(dn);		   /* clean number */
238   if (sourhi&0x80000000) dn->bits=DECNEG; /* set sign if negative */
239 
240   msd=COMBMSD[comb];		   /* decode the combination field */
241   exp=COMBEXP[comb];		   /* .. */
242 
243   if (exp==3) {			   /* is a special */
244     if (msd==0) {
245       dn->bits|=DECINF;
246       return dn;		   /* no coefficient needed */
247       }
248     else if (sourhi&0x02000000) dn->bits|=DECSNAN;
249     else dn->bits|=DECNAN;
250     msd=0;			   /* no top digit */
251     }
252    else {			   /* is a finite number */
253     dn->exponent=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias; /* unbiased */
254     }
255 
256   /* get the coefficient */
257   sourhi&=0x0003ffff;		   /* clean coefficient continuation */
258   if (msd) {			   /* non-zero msd */
259     sourhi|=msd<<18;		   /* prefix to coefficient */
260     need=6;			   /* process 6 declets */
261     }
262    else { /* msd=0 */
263     if (!sourhi) {		   /* top word 0 */
264       if (!sourlo) return dn;	   /* easy: coefficient is 0 */
265       need=3;			   /* process at least 3 declets */
266       if (sourlo&0xc0000000) need++; /* process 4 declets */
267       /* [could reduce some more, here] */
268       }
269      else {			   /* some bits in top word, msd=0 */
270       need=4;			   /* process at least 4 declets */
271       if (sourhi&0x0003ff00) need++; /* top declet!=0, process 5 */
272       }
273     } /*msd=0 */
274 
275   decDigitsFromDPD(dn, sourar, need);	/* process declets */
276   return dn;
277   } /* decimal64ToNumber */
278 
279 
280 /* ------------------------------------------------------------------ */
281 /* to-scientific-string -- conversion to numeric string		      */
282 /* to-engineering-string -- conversion to numeric string	      */
283 /*								      */
284 /*   decimal64ToString(d64, string);				      */
285 /*   decimal64ToEngString(d64, string);				      */
286 /*								      */
287 /*  d64 is the decimal64 format number to convert		      */
288 /*  string is the string where the result will be laid out	      */
289 /*								      */
290 /*  string must be at least 24 characters			      */
291 /*								      */
292 /*  No error is possible, and no status can be set.		      */
293 /* ------------------------------------------------------------------ */
decimal64ToEngString(const decimal64 * d64,char * string)294 char * decimal64ToEngString(const decimal64 *d64, char *string){
295   decNumber dn;				/* work */
296   decimal64ToNumber(d64, &dn);
297   decNumberToEngString(&dn, string);
298   return string;
299   } /* decimal64ToEngString */
300 
decimal64ToString(const decimal64 * d64,char * string)301 char * decimal64ToString(const decimal64 *d64, char *string){
302   uInt msd;			   /* coefficient MSD */
303   Int  exp;			   /* exponent top two bits or full */
304   uInt comb;			   /* combination field */
305   char *cstart;			   /* coefficient start */
306   char *c;			   /* output pointer in string */
307   const uInt *pu;		   /* work */
308   char *s, *t;			   /* .. (source, target) */
309   Int  dpd;			   /* .. */
310   Int  pre, e;			   /* .. */
311   const uByte *u;		   /* .. */
312 
313   uInt sourar[2];		   /* source 64-bit */
314   #define sourhi sourar[1]	   /* name the word with the sign */
315   #define sourlo sourar[0]	   /* and the lower word */
316 
317   /* load source from storage; this is endian */
318   pu=(const uInt *)d64->bytes;	   /* overlay */
319   if (DECLITEND) {
320     sourlo=pu[0];		   /* directly load the low int */
321     sourhi=pu[1];		   /* then the high int */
322     }
323    else {
324     sourhi=pu[0];		   /* directly load the high int */
325     sourlo=pu[1];		   /* then the low int */
326     }
327 
328   c=string;			   /* where result will go */
329   if (((Int)sourhi)<0) *c++='-';   /* handle sign */
330 
331   comb=(sourhi>>26)&0x1f;	   /* combination field */
332   msd=COMBMSD[comb];		   /* decode the combination field */
333   exp=COMBEXP[comb];		   /* .. */
334 
335   if (exp==3) {
336     if (msd==0) {		   /* infinity */
337       strcpy(c,	  "Inf");
338       strcpy(c+3, "inity");
339       return string;		   /* easy */
340       }
341     if (sourhi&0x02000000) *c++='s'; /* sNaN */
342     strcpy(c, "NaN");		   /* complete word */
343     c+=3;			   /* step past */
344     if (sourlo==0 && (sourhi&0x0003ffff)==0) return string; /* zero payload */
345     /* otherwise drop through to add integer; set correct exp */
346     exp=0; msd=0;		   /* setup for following code */
347     }
348    else exp=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias;
349 
350   /* convert 16 digits of significand to characters */
351   cstart=c;			   /* save start of coefficient */
352   if (msd) *c++='0'+(char)msd;	   /* non-zero most significant digit */
353 
354   /* Now decode the declets.  After extracting each one, it is */
355   /* decoded to binary and then to a 4-char sequence by table lookup; */
356   /* the 4-chars are a 1-char length (significant digits, except 000 */
357   /* has length 0).  This allows us to left-align the first declet */
358   /* with non-zero content, then remaining ones are full 3-char */
359   /* length.  We use fixed-length memcpys because variable-length */
360   /* causes a subroutine call in GCC.  (These are length 4 for speed */
361   /* and are safe because the array has an extra terminator byte.) */
362   #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4];			  \
363 		   if (c!=cstart) {memcpy(c, u+1, 4); c+=3;}	  \
364 		    else if (*u)  {memcpy(c, u+4-*u, 4); c+=*u;}
365 
366   dpd=(sourhi>>8)&0x3ff;		     /* declet 1 */
367   dpd2char;
368   dpd=((sourhi&0xff)<<2) | (sourlo>>30);     /* declet 2 */
369   dpd2char;
370   dpd=(sourlo>>20)&0x3ff;		     /* declet 3 */
371   dpd2char;
372   dpd=(sourlo>>10)&0x3ff;		     /* declet 4 */
373   dpd2char;
374   dpd=(sourlo)&0x3ff;			     /* declet 5 */
375   dpd2char;
376 
377   if (c==cstart) *c++='0';	   /* all zeros -- make 0 */
378 
379   if (exp==0) {			   /* integer or NaN case -- easy */
380     *c='\0';			   /* terminate */
381     return string;
382     }
383 
384   /* non-0 exponent */
385   e=0;				   /* assume no E */
386   pre=c-cstart+exp;
387   /* [here, pre-exp is the digits count (==1 for zero)] */
388   if (exp>0 || pre<-5) {	   /* need exponential form */
389     e=pre-1;			   /* calculate E value */
390     pre=1;			   /* assume one digit before '.' */
391     } /* exponential form */
392 
393   /* modify the coefficient, adding 0s, '.', and E+nn as needed */
394   s=c-1;			   /* source (LSD) */
395   if (pre>0) {			   /* ddd.ddd (plain), perhaps with E */
396     char *dotat=cstart+pre;
397     if (dotat<c) {		   /* if embedded dot needed... */
398       t=c;				/* target */
399       for (; s>=dotat; s--, t--) *t=*s; /* open the gap; leave t at gap */
400       *t='.';				/* insert the dot */
401       c++;				/* length increased by one */
402       }
403 
404     /* finally add the E-part, if needed; it will never be 0, and has */
405     /* a maximum length of 3 digits */
406     if (e!=0) {
407       *c++='E';			   /* starts with E */
408       *c++='+';			   /* assume positive */
409       if (e<0) {
410 	*(c-1)='-';		   /* oops, need '-' */
411 	e=-e;			   /* uInt, please */
412 	}
413       u=&BIN2CHAR[e*4];		   /* -> length byte */
414       memcpy(c, u+4-*u, 4);	   /* copy fixed 4 characters [is safe] */
415       c+=*u;			   /* bump pointer appropriately */
416       }
417     *c='\0';			   /* add terminator */
418     /*printf("res %s\n", string); */
419     return string;
420     } /* pre>0 */
421 
422   /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
423   t=c+1-pre;
424   *(t+1)='\0';				/* can add terminator now */
425   for (; s>=cstart; s--, t--) *t=*s;	/* shift whole coefficient right */
426   c=cstart;
427   *c++='0';				/* always starts with 0. */
428   *c++='.';
429   for (; pre<0; pre++) *c++='0';	/* add any 0's after '.' */
430   /*printf("res %s\n", string); */
431   return string;
432   } /* decimal64ToString */
433 
434 /* ------------------------------------------------------------------ */
435 /* to-number -- conversion from numeric string			      */
436 /*								      */
437 /*   decimal64FromString(result, string, set);			      */
438 /*								      */
439 /*  result  is the decimal64 format number which gets the result of   */
440 /*	    the conversion					      */
441 /*  *string is the character string which should contain a valid      */
442 /*	    number (which may be a special value)		      */
443 /*  set	    is the context					      */
444 /*								      */
445 /* The context is supplied to this routine is used for error handling */
446 /* (setting of status and traps) and for the rounding mode, only.     */
447 /* If an error occurs, the result will be a valid decimal64 NaN.      */
448 /* ------------------------------------------------------------------ */
decimal64FromString(decimal64 * result,const char * string,decContext * set)449 decimal64 * decimal64FromString(decimal64 *result, const char *string,
450 				decContext *set) {
451   decContext dc;			     /* work */
452   decNumber dn;				     /* .. */
453 
454   decContextDefault(&dc, DEC_INIT_DECIMAL64); /* no traps, please */
455   dc.round=set->round;			      /* use supplied rounding */
456 
457   decNumberFromString(&dn, string, &dc);     /* will round if needed */
458 
459   decimal64FromNumber(result, &dn, &dc);
460   if (dc.status!=0) {			     /* something happened */
461     decContextSetStatus(set, dc.status);     /* .. pass it on */
462     }
463   return result;
464   } /* decimal64FromString */
465 
466 /* ------------------------------------------------------------------ */
467 /* decimal64IsCanonical -- test whether encoding is canonical	      */
468 /*   d64 is the source decimal64				      */
469 /*   returns 1 if the encoding of d64 is canonical, 0 otherwise	      */
470 /* No error is possible.					      */
471 /* ------------------------------------------------------------------ */
decimal64IsCanonical(const decimal64 * d64)472 uint32_t decimal64IsCanonical(const decimal64 *d64) {
473   decNumber dn;				/* work */
474   decimal64 canon;			/* .. */
475   decContext dc;			/* .. */
476   decContextDefault(&dc, DEC_INIT_DECIMAL64);
477   decimal64ToNumber(d64, &dn);
478   decimal64FromNumber(&canon, &dn, &dc);/* canon will now be canonical */
479   return memcmp(d64, &canon, DECIMAL64_Bytes)==0;
480   } /* decimal64IsCanonical */
481 
482 /* ------------------------------------------------------------------ */
483 /* decimal64Canonical -- copy an encoding, ensuring it is canonical   */
484 /*   d64 is the source decimal64				      */
485 /*   result is the target (may be the same decimal64)		      */
486 /*   returns result						      */
487 /* No error is possible.					      */
488 /* ------------------------------------------------------------------ */
decimal64Canonical(decimal64 * result,const decimal64 * d64)489 decimal64 * decimal64Canonical(decimal64 *result, const decimal64 *d64) {
490   decNumber dn;				/* work */
491   decContext dc;			/* .. */
492   decContextDefault(&dc, DEC_INIT_DECIMAL64);
493   decimal64ToNumber(d64, &dn);
494   decimal64FromNumber(result, &dn, &dc);/* result will now be canonical */
495   return result;
496   } /* decimal64Canonical */
497 
498 #if DECTRACE || DECCHECK
499 /* Macros for accessing decimal64 fields.  These assume the
500    argument is a reference (pointer) to the decimal64 structure,
501    and the decimal64 is in network byte order (big-endian) */
502 /* Get sign */
503 #define decimal64Sign(d)       ((unsigned)(d)->bytes[0]>>7)
504 
505 /* Get combination field */
506 #define decimal64Comb(d)       (((d)->bytes[0] & 0x7c)>>2)
507 
508 /* Get exponent continuation [does not remove bias] */
509 #define decimal64ExpCon(d)     ((((d)->bytes[0] & 0x03)<<6)	      \
510 			     | ((unsigned)(d)->bytes[1]>>2))
511 
512 /* Set sign [this assumes sign previously 0] */
513 #define decimal64SetSign(d, b) {				      \
514   (d)->bytes[0]|=((unsigned)(b)<<7);}
515 
516 /* Set exponent continuation [does not apply bias] */
517 /* This assumes range has been checked and exponent previously 0; */
518 /* type of exponent must be unsigned */
519 #define decimal64SetExpCon(d, e) {				      \
520   (d)->bytes[0]|=(uint8_t)((e)>>6);				      \
521   (d)->bytes[1]|=(uint8_t)(((e)&0x3F)<<2);}
522 
523 /* ------------------------------------------------------------------ */
524 /* decimal64Show -- display a decimal64 in hexadecimal [debug aid]    */
525 /*   d64 -- the number to show					      */
526 /* ------------------------------------------------------------------ */
527 /* Also shows sign/cob/expconfields extracted */
decimal64Show(const decimal64 * d64)528 void decimal64Show(const decimal64 *d64) {
529   char buf[DECIMAL64_Bytes*2+1];
530   Int i, j=0;
531 
532   if (DECLITEND) {
533     for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
534       sprintf(&buf[j], "%02x", d64->bytes[7-i]);
535       }
536     printf(" D64> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
537 	   d64->bytes[7]>>7, (d64->bytes[7]>>2)&0x1f,
538 	   ((d64->bytes[7]&0x3)<<6)| (d64->bytes[6]>>2));
539     }
540    else { /* big-endian */
541     for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {
542       sprintf(&buf[j], "%02x", d64->bytes[i]);
543       }
544     printf(" D64> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
545 	   decimal64Sign(d64), decimal64Comb(d64), decimal64ExpCon(d64));
546     }
547   } /* decimal64Show */
548 #endif
549 
550 /* ================================================================== */
551 /* Shared utility routines and tables				      */
552 /* ================================================================== */
553 /* define and include the conversion tables to use for shared code */
554 #if DECDPUN==3
555   #define DEC_DPD2BIN 1
556 #else
557   #define DEC_DPD2BCD 1
558 #endif
559 #include "libdecnumber/decDPD.h"
560 
561 /* The maximum number of decNumberUnits needed for a working copy of */
562 /* the units array is the ceiling of digits/DECDPUN, where digits is */
563 /* the maximum number of digits in any of the formats for which this */
564 /* is used.  decimal128.h must not be included in this module, so, as */
565 /* a very special case, that number is defined as a literal here. */
566 #define DECMAX754   34
567 #define DECMAXUNITS ((DECMAX754+DECDPUN-1)/DECDPUN)
568 
569 /* ------------------------------------------------------------------ */
570 /* Combination field lookup tables (uInts to save measurable work)    */
571 /*								      */
572 /*	COMBEXP - 2-bit most-significant-bits of exponent	      */
573 /*		  [11 if an Infinity or NaN]			      */
574 /*	COMBMSD - 4-bit most-significant-digit			      */
575 /*		  [0=Infinity, 1=NaN if COMBEXP=11]		      */
576 /*								      */
577 /* Both are indexed by the 5-bit combination field (0-31)	      */
578 /* ------------------------------------------------------------------ */
579 const uInt COMBEXP[32]={0, 0, 0, 0, 0, 0, 0, 0,
580 			1, 1, 1, 1, 1, 1, 1, 1,
581 			2, 2, 2, 2, 2, 2, 2, 2,
582 			0, 0, 1, 1, 2, 2, 3, 3};
583 const uInt COMBMSD[32]={0, 1, 2, 3, 4, 5, 6, 7,
584 			0, 1, 2, 3, 4, 5, 6, 7,
585 			0, 1, 2, 3, 4, 5, 6, 7,
586 			8, 9, 8, 9, 8, 9, 0, 1};
587 
588 /* ------------------------------------------------------------------ */
589 /* decDigitsToDPD -- pack coefficient into DPD form		      */
590 /*								      */
591 /*   dn	  is the source number (assumed valid, max DECMAX754 digits)  */
592 /*   targ is 1, 2, or 4-element uInt array, which the caller must     */
593 /*	  have cleared to zeros					      */
594 /*   shift is the number of 0 digits to add on the right (normally 0) */
595 /*								      */
596 /* The coefficient must be known small enough to fit.  The full	      */
597 /* coefficient is copied, including the leading 'odd' digit.  This    */
598 /* digit is retrieved and packed into the combination field by the    */
599 /* caller.							      */
600 /*								      */
601 /* The target uInts are altered only as necessary to receive the      */
602 /* digits of the decNumber.  When more than one uInt is needed, they  */
603 /* are filled from left to right (that is, the uInt at offset 0 will  */
604 /* end up with the least-significant digits).			      */
605 /*								      */
606 /* shift is used for 'fold-down' padding.			      */
607 /*								      */
608 /* No error is possible.					      */
609 /* ------------------------------------------------------------------ */
610 #if DECDPUN<=4
611 /* Constant multipliers for divide-by-power-of five using reciprocal */
612 /* multiply, after removing powers of 2 by shifting, and final shift */
613 /* of 17 [we only need up to **4] */
614 static const uInt multies[]={131073, 26215, 5243, 1049, 210};
615 /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
616 #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
617 #endif
decDigitsToDPD(const decNumber * dn,uInt * targ,Int shift)618 void decDigitsToDPD(const decNumber *dn, uInt *targ, Int shift) {
619   Int  cut;		      /* work */
620   Int  digits=dn->digits;     /* digit countdown */
621   uInt dpd;		      /* densely packed decimal value */
622   uInt bin;		      /* binary value 0-999 */
623   uInt *uout=targ;	      /* -> current output uInt */
624   uInt	uoff=0;		      /* -> current output offset [from right] */
625   const Unit *inu=dn->lsu;    /* -> current input unit */
626   Unit	uar[DECMAXUNITS];     /* working copy of units, iff shifted */
627   #if DECDPUN!=3	      /* not fast path */
628     Unit in;		      /* current unit */
629   #endif
630 
631   if (shift!=0) {	      /* shift towards most significant required */
632     /* shift the units array to the left by pad digits and copy */
633     /* [this code is a special case of decShiftToMost, which could */
634     /* be used instead if exposed and the array were copied first] */
635     const Unit *source;			/* .. */
636     Unit  *target, *first;		/* .. */
637     uInt  next=0;			/* work */
638 
639     source=dn->lsu+D2U(digits)-1;	/* where msu comes from */
640     target=uar+D2U(digits)-1+D2U(shift);/* where upper part of first cut goes */
641     cut=DECDPUN-MSUDIGITS(shift);	/* where to slice */
642     if (cut==0) {			/* unit-boundary case */
643       for (; source>=dn->lsu; source--, target--) *target=*source;
644       }
645      else {
646       first=uar+D2U(digits+shift)-1;	/* where msu will end up */
647       for (; source>=dn->lsu; source--, target--) {
648 	/* split the source Unit and accumulate remainder for next */
649 	#if DECDPUN<=4
650 	  uInt quot=QUOT10(*source, cut);
651 	  uInt rem=*source-quot*DECPOWERS[cut];
652 	  next+=quot;
653 	#else
654 	  uInt rem=*source%DECPOWERS[cut];
655 	  next+=*source/DECPOWERS[cut];
656 	#endif
657 	if (target<=first) *target=(Unit)next; /* write to target iff valid */
658 	next=rem*DECPOWERS[DECDPUN-cut];       /* save remainder for next Unit */
659 	}
660       } /* shift-move */
661     /* propagate remainder to one below and clear the rest */
662     for (; target>=uar; target--) {
663       *target=(Unit)next;
664       next=0;
665       }
666     digits+=shift;		   /* add count (shift) of zeros added */
667     inu=uar;			   /* use units in working array */
668     }
669 
670   /* now densely pack the coefficient into DPD declets */
671 
672   #if DECDPUN!=3		   /* not fast path */
673     in=*inu;			   /* current unit */
674     cut=0;			   /* at lowest digit */
675     bin=0;			   /* [keep compiler quiet] */
676   #endif
677 
678   while (digits > 0) {             /* each output bunch */
679     #if DECDPUN==3		   /* fast path, 3-at-a-time */
680       bin=*inu;			   /* 3 digits ready for convert */
681       digits-=3;		   /* [may go negative] */
682       inu++;			   /* may need another */
683 
684     #else			   /* must collect digit-by-digit */
685       Unit dig;			   /* current digit */
686       Int j;			   /* digit-in-declet count */
687       for (j=0; j<3; j++) {
688 	#if DECDPUN<=4
689 	  Unit temp=(Unit)((uInt)(in*6554)>>16);
690 	  dig=(Unit)(in-X10(temp));
691 	  in=temp;
692 	#else
693 	  dig=in%10;
694 	  in=in/10;
695 	#endif
696 	if (j==0) bin=dig;
697 	 else if (j==1)	 bin+=X10(dig);
698 	 else /* j==2 */ bin+=X100(dig);
699 	digits--;
700 	if (digits==0) break;	   /* [also protects *inu below] */
701 	cut++;
702 	if (cut==DECDPUN) {inu++; in=*inu; cut=0;}
703 	}
704     #endif
705     /* here there are 3 digits in bin, or have used all input digits */
706 
707     dpd=BIN2DPD[bin];
708 
709     /* write declet to uInt array */
710     *uout|=dpd<<uoff;
711     uoff+=10;
712     if (uoff<32) continue;	   /* no uInt boundary cross */
713     uout++;
714     uoff-=32;
715     *uout|=dpd>>(10-uoff);	   /* collect top bits */
716     } /* n declets */
717   return;
718   } /* decDigitsToDPD */
719 
720 /* ------------------------------------------------------------------ */
721 /* decDigitsFromDPD -- unpack a format's coefficient		      */
722 /*								      */
723 /*   dn is the target number, with 7, 16, or 34-digit space.	      */
724 /*   sour is a 1, 2, or 4-element uInt array containing only declets  */
725 /*   declets is the number of (right-aligned) declets in sour to      */
726 /*     be processed.  This may be 1 more than the obvious number in   */
727 /*     a format, as any top digit is prefixed to the coefficient      */
728 /*     continuation field.  It also may be as small as 1, as the      */
729 /*     caller may pre-process leading zero declets.		      */
730 /*								      */
731 /* When doing the 'extra declet' case care is taken to avoid writing  */
732 /* extra digits when there are leading zeros, as these could overflow */
733 /* the units array when DECDPUN is not 3.			      */
734 /*								      */
735 /* The target uInts are used only as necessary to process declets     */
736 /* declets into the decNumber.	When more than one uInt is needed,    */
737 /* they are used from left to right (that is, the uInt at offset 0    */
738 /* provides the least-significant digits).			      */
739 /*								      */
740 /* dn->digits is set, but not the sign or exponent.		      */
741 /* No error is possible [the redundant 888 codes are allowed].	      */
742 /* ------------------------------------------------------------------ */
decDigitsFromDPD(decNumber * dn,const uInt * sour,Int declets)743 void decDigitsFromDPD(decNumber *dn, const uInt *sour, Int declets) {
744 
745   uInt	dpd;			   /* collector for 10 bits */
746   Int	n;			   /* counter */
747   Unit	*uout=dn->lsu;		   /* -> current output unit */
748   Unit	*last=uout;		   /* will be unit containing msd */
749   const uInt *uin=sour;		   /* -> current input uInt */
750   uInt	uoff=0;			   /* -> current input offset [from right] */
751 
752   #if DECDPUN!=3
753   uInt	bcd;			   /* BCD result */
754   uInt	nibble;			   /* work */
755   Unit	out=0;			   /* accumulator */
756   Int	cut=0;			   /* power of ten in current unit */
757   #endif
758   #if DECDPUN>4
759   uInt const *pow;		   /* work */
760   #endif
761 
762   /* Expand the densely-packed integer, right to left */
763   for (n=declets-1; n>=0; n--) {   /* count down declets of 10 bits */
764     dpd=*uin>>uoff;
765     uoff+=10;
766     if (uoff>32) {		   /* crossed uInt boundary */
767       uin++;
768       uoff-=32;
769       dpd|=*uin<<(10-uoff);	   /* get waiting bits */
770       }
771     dpd&=0x3ff;			   /* clear uninteresting bits */
772 
773   #if DECDPUN==3
774     if (dpd==0) *uout=0;
775      else {
776       *uout=DPD2BIN[dpd];	   /* convert 10 bits to binary 0-999 */
777       last=uout;		   /* record most significant unit */
778       }
779     uout++;
780     } /* n */
781 
782   #else /* DECDPUN!=3 */
783     if (dpd==0) {		   /* fastpath [e.g., leading zeros] */
784       /* write out three 0 digits (nibbles); out may have digit(s) */
785       cut++;
786       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
787       if (n==0) break;		   /* [as below, works even if MSD=0] */
788       cut++;
789       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
790       cut++;
791       if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
792       continue;
793       }
794 
795     bcd=DPD2BCD[dpd];		   /* convert 10 bits to 12 bits BCD */
796 
797     /* now accumulate the 3 BCD nibbles into units */
798     nibble=bcd & 0x00f;
799     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
800     cut++;
801     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
802     bcd>>=4;
803 
804     /* if this is the last declet and the remaining nibbles in bcd */
805     /* are 00 then process no more nibbles, because this could be */
806     /* the 'odd' MSD declet and writing any more Units would then */
807     /* overflow the unit array */
808     if (n==0 && !bcd) break;
809 
810     nibble=bcd & 0x00f;
811     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
812     cut++;
813     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
814     bcd>>=4;
815 
816     nibble=bcd & 0x00f;
817     if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);
818     cut++;
819     if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}
820     } /* n */
821   if (cut!=0) {				/* some more left over */
822     *uout=out;				/* write out final unit */
823     if (out) last=uout;			/* and note if non-zero */
824     }
825   #endif
826 
827   /* here, last points to the most significant unit with digits; */
828   /* inspect it to get the final digits count -- this is essentially */
829   /* the same code as decGetDigits in decNumber.c */
830   dn->digits=(last-dn->lsu)*DECDPUN+1;	/* floor of digits, plus */
831 					/* must be at least 1 digit */
832   #if DECDPUN>1
833   if (*last<10) return;			/* common odd digit or 0 */
834   dn->digits++;				/* must be 2 at least */
835   #if DECDPUN>2
836   if (*last<100) return;		/* 10-99 */
837   dn->digits++;				/* must be 3 at least */
838   #if DECDPUN>3
839   if (*last<1000) return;		/* 100-999 */
840   dn->digits++;				/* must be 4 at least */
841   #if DECDPUN>4
842   for (pow=&DECPOWERS[4]; *last>=*pow; pow++) dn->digits++;
843   #endif
844   #endif
845   #endif
846   #endif
847   return;
848   } /*decDigitsFromDPD */
849