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