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