Add decNumber library
Before adoption: this commit came in with the history the project adopted, so no landing records it.
The library adds support for decimal numbers of arbitrary length. Downloaded from ICU, under ICU 1.8.1 license http://download.icu-project.org/files/decNumber/decNumber-icu-368.zip
authored by Leonid S. Usov · committed by William Langford · parent 37b2d21 · Browse files · 36 files·+20503 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
36 files+20503 added−0 removed
- other:+20503 added−0 removed
Provenance
- Commit
b6be13d- Tree
8fc224d- Author
Leonid S. Usov <leonid@practi.net>- Committer
William Langford <wlangfor@gmail.com>- Parent
37b2d21
36 files changed+20503 added−0 removed
modified:docs/content/download/default.yml+4 added
11 unmodified lines12131415161718192021222324172 unmodified linesExpand all11 unmodified lines
jq is licensed under the MIT license. For all of the gory details, read the file `COPYING` in the source distribution.
jq uses a C library for decimal number support. This is an ICU 1.8.1 licensed code obtained from the ICU downloads archive http://download.icu-project.org/files/decNumber/decNumber-icu-368.zip.
### Linux
* jq 1.5 is in the official [Debian](https://packages.debian.org/jq) and [Ubuntu](http://packages.ubuntu.com/jq) repositories. Install using172 unmodified linesExpand alladded:src/decNumber/decBasic.c+3908 added
1+/* ------------------------------------------------------------------ */2+/* decBasic.c -- common base code for Basic decimal types */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises code that is shared between decDouble and */20+/* decQuad (but not decSingle). The main arithmetic operations are */21+/* here (Add, Subtract, Multiply, FMA, and Division operators). */22+/* */23+/* Unlike decNumber, parameterization takes place at compile time */24+/* rather than at runtime. The parameters are set in the decDouble.c */25+/* (etc.) files, which then include this one to produce the compiled */26+/* code. The functions here, therefore, are code shared between */27+/* multiple formats. */28+/* */29+/* This must be included after decCommon.c. */30+/* ------------------------------------------------------------------ */31+// Names here refer to decFloat rather than to decDouble, etc., and32+// the functions are in strict alphabetical order.33+34+// The compile-time flags SINGLE, DOUBLE, and QUAD are set up in35+// decCommon.c36+#if !defined(QUAD)37+ #error decBasic.c must be included after decCommon.c38+#endif39+#if SINGLE40+ #error Routines in decBasic.c are for decDouble and decQuad only41+#endif42+43+/* Private constants */44+#define DIVIDE 0x80000000 // Divide operations [as flags]45+#define REMAINDER 0x40000000 // ..46+#define DIVIDEINT 0x20000000 // ..47+#define REMNEAR 0x10000000 // ..48+49+/* Private functions (local, used only by routines in this module) */50+static decFloat *decDivide(decFloat *, const decFloat *,51+ const decFloat *, decContext *, uInt);52+static decFloat *decCanonical(decFloat *, const decFloat *);53+static void decFiniteMultiply(bcdnum *, uByte *, const decFloat *,54+ const decFloat *);55+static decFloat *decInfinity(decFloat *, const decFloat *);56+static decFloat *decInvalid(decFloat *, decContext *);57+static decFloat *decNaNs(decFloat *, const decFloat *, const decFloat *,58+ decContext *);59+static Int decNumCompare(const decFloat *, const decFloat *, Flag);60+static decFloat *decToIntegral(decFloat *, const decFloat *, decContext *,61+ enum rounding, Flag);62+static uInt decToInt32(const decFloat *, decContext *, enum rounding,63+ Flag, Flag);64+65+/* ------------------------------------------------------------------ */66+/* decCanonical -- copy a decFloat, making canonical */67+/* */68+/* result gets the canonicalized df */69+/* df is the decFloat to copy and make canonical */70+/* returns result */71+/* */72+/* This is exposed via decFloatCanonical for Double and Quad only. */73+/* This works on specials, too; no error or exception is possible. */74+/* ------------------------------------------------------------------ */75+static decFloat * decCanonical(decFloat *result, const decFloat *df) {76+ uInt encode, precode, dpd; // work77+ uInt inword, uoff, canon; // ..78+ Int n; // counter (down)79+ if (df!=result) *result=*df; // effect copy if needed80+ if (DFISSPECIAL(result)) {81+ if (DFISINF(result)) return decInfinity(result, df); // clean Infinity82+ // is a NaN83+ DFWORD(result, 0)&=~ECONNANMASK; // clear ECON except selector84+ if (DFISCCZERO(df)) return result; // coefficient continuation is 085+ // drop through to check payload86+ }87+ // return quickly if the coefficient continuation is canonical88+ { // declare block89+ #if DOUBLE90+ uInt sourhi=DFWORD(df, 0);91+ uInt sourlo=DFWORD(df, 1);92+ if (CANONDPDOFF(sourhi, 8)93+ && CANONDPDTWO(sourhi, sourlo, 30)94+ && CANONDPDOFF(sourlo, 20)95+ && CANONDPDOFF(sourlo, 10)96+ && CANONDPDOFF(sourlo, 0)) return result;97+ #elif QUAD98+ uInt sourhi=DFWORD(df, 0);99+ uInt sourmh=DFWORD(df, 1);100+ uInt sourml=DFWORD(df, 2);101+ uInt sourlo=DFWORD(df, 3);102+ if (CANONDPDOFF(sourhi, 4)103+ && CANONDPDTWO(sourhi, sourmh, 26)104+ && CANONDPDOFF(sourmh, 16)105+ && CANONDPDOFF(sourmh, 6)106+ && CANONDPDTWO(sourmh, sourml, 28)107+ && CANONDPDOFF(sourml, 18)108+ && CANONDPDOFF(sourml, 8)109+ && CANONDPDTWO(sourml, sourlo, 30)110+ && CANONDPDOFF(sourlo, 20)111+ && CANONDPDOFF(sourlo, 10)112+ && CANONDPDOFF(sourlo, 0)) return result;113+ #endif114+ } // block115+116+ // Loop to repair a non-canonical coefficent, as needed117+ inword=DECWORDS-1; // current input word118+ uoff=0; // bit offset of declet119+ encode=DFWORD(result, inword);120+ for (n=DECLETS-1; n>=0; n--) { // count down declets of 10 bits121+ dpd=encode>>uoff;122+ uoff+=10;123+ if (uoff>32) { // crossed uInt boundary124+ inword--;125+ encode=DFWORD(result, inword);126+ uoff-=32;127+ dpd|=encode<<(10-uoff); // get pending bits128+ }129+ dpd&=0x3ff; // clear uninteresting bits130+ if (dpd<0x16e) continue; // must be canonical131+ canon=BIN2DPD[DPD2BIN[dpd]]; // determine canonical declet132+ if (canon==dpd) continue; // have canonical declet133+ // need to replace declet134+ if (uoff>=10) { // all within current word135+ encode&=~(0x3ff<<(uoff-10)); // clear the 10 bits ready for replace136+ encode|=canon<<(uoff-10); // insert the canonical form137+ DFWORD(result, inword)=encode; // .. and save138+ continue;139+ }140+ // straddled words141+ precode=DFWORD(result, inword+1); // get previous142+ precode&=0xffffffff>>(10-uoff); // clear top bits143+ DFWORD(result, inword+1)=precode|(canon<<(32-(10-uoff)));144+ encode&=0xffffffff<<uoff; // clear bottom bits145+ encode|=canon>>(10-uoff); // insert canonical146+ DFWORD(result, inword)=encode; // .. and save147+ } // n148+ return result;149+ } // decCanonical150+151+/* ------------------------------------------------------------------ */152+/* decDivide -- divide operations */153+/* */154+/* result gets the result of dividing dfl by dfr: */155+/* dfl is the first decFloat (lhs) */156+/* dfr is the second decFloat (rhs) */157+/* set is the context */158+/* op is the operation selector */159+/* returns result */160+/* */161+/* op is one of DIVIDE, REMAINDER, DIVIDEINT, or REMNEAR. */162+/* ------------------------------------------------------------------ */163+#define DIVCOUNT 0 // 1 to instrument subtractions counter164+#define DIVBASE ((uInt)BILLION) // the base used for divide165+#define DIVOPLEN DECPMAX9 // operand length ('digits' base 10**9)166+#define DIVACCLEN (DIVOPLEN*3) // accumulator length (ditto)167+static decFloat * decDivide(decFloat *result, const decFloat *dfl,168+ const decFloat *dfr, decContext *set, uInt op) {169+ decFloat quotient; // for remainders170+ bcdnum num; // for final conversion171+ uInt acc[DIVACCLEN]; // coefficent in base-billion ..172+ uInt div[DIVOPLEN]; // divisor in base-billion ..173+ uInt quo[DIVOPLEN+1]; // quotient in base-billion ..174+ uByte bcdacc[(DIVOPLEN+1)*9+2]; // for quotient in BCD, +1, +1175+ uInt *msua, *msud, *msuq; // -> msu of acc, div, and quo176+ Int divunits, accunits; // lengths177+ Int quodigits; // digits in quotient178+ uInt *lsua, *lsuq; // -> current acc and quo lsus179+ Int length, multiplier; // work180+ uInt carry, sign; // ..181+ uInt *ua, *ud, *uq; // ..182+ uByte *ub; // ..183+ uInt uiwork; // for macros184+ uInt divtop; // top unit of div adjusted for estimating185+ #if DIVCOUNT186+ static uInt maxcount=0; // worst-seen subtractions count187+ uInt divcount=0; // subtractions count [this divide]188+ #endif189+190+ // calculate sign191+ num.sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;192+193+ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { // either is special?194+ // NaNs are handled as usual195+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);196+ // one or two infinities197+ if (DFISINF(dfl)) {198+ if (DFISINF(dfr)) return decInvalid(result, set); // Two infinities bad199+ if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); // as is rem200+ // Infinity/x is infinite and quiet, even if x=0201+ DFWORD(result, 0)=num.sign;202+ return decInfinity(result, result);203+ }204+ // must be x/Infinity -- remainders are lhs205+ if (op&(REMAINDER|REMNEAR)) return decCanonical(result, dfl);206+ // divides: return zero with correct sign and exponent depending207+ // on op (Etiny for divide, 0 for divideInt)208+ decFloatZero(result);209+ if (op==DIVIDEINT) DFWORD(result, 0)|=num.sign; // add sign210+ else DFWORD(result, 0)=num.sign; // zeros the exponent, too211+ return result;212+ }213+ // next, handle zero operands (x/0 and 0/x)214+ if (DFISZERO(dfr)) { // x/0215+ if (DFISZERO(dfl)) { // 0/0 is undefined216+ decFloatZero(result);217+ DFWORD(result, 0)=DECFLOAT_qNaN;218+ set->status|=DEC_Division_undefined;219+ return result;220+ }221+ if (op&(REMAINDER|REMNEAR)) return decInvalid(result, set); // bad rem222+ set->status|=DEC_Division_by_zero;223+ DFWORD(result, 0)=num.sign;224+ return decInfinity(result, result); // x/0 -> signed Infinity225+ }226+ num.exponent=GETEXPUN(dfl)-GETEXPUN(dfr); // ideal exponent227+ if (DFISZERO(dfl)) { // 0/x (x!=0)228+ // if divide, result is 0 with ideal exponent; divideInt has229+ // exponent=0, remainders give zero with lower exponent230+ if (op&DIVIDEINT) {231+ decFloatZero(result);232+ DFWORD(result, 0)|=num.sign; // add sign233+ return result;234+ }235+ if (!(op&DIVIDE)) { // a remainder236+ // exponent is the minimum of the operands237+ num.exponent=MINI(GETEXPUN(dfl), GETEXPUN(dfr));238+ // if the result is zero the sign shall be sign of dfl239+ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;240+ }241+ bcdacc[0]=0;242+ num.msd=bcdacc; // -> 0243+ num.lsd=bcdacc; // ..244+ return decFinalize(result, &num, set); // [divide may clamp exponent]245+ } // 0/x246+ // [here, both operands are known to be finite and non-zero]247+248+ // extract the operand coefficents into 'units' which are249+ // base-billion; the lhs is high-aligned in acc and the msu of both250+ // acc and div is at the right-hand end of array (offset length-1);251+ // the quotient can need one more unit than the operands as digits252+ // in it are not necessarily aligned neatly; further, the quotient253+ // may not start accumulating until after the end of the initial254+ // operand in acc if that is small (e.g., 1) so the accumulator255+ // must have at least that number of units extra (at the ls end)256+ GETCOEFFBILL(dfl, acc+DIVACCLEN-DIVOPLEN);257+ GETCOEFFBILL(dfr, div);258+ // zero the low uInts of acc259+ acc[0]=0;260+ acc[1]=0;261+ acc[2]=0;262+ acc[3]=0;263+ #if DOUBLE264+ #if DIVOPLEN!=2265+ #error Unexpected Double DIVOPLEN266+ #endif267+ #elif QUAD268+ acc[4]=0;269+ acc[5]=0;270+ acc[6]=0;271+ acc[7]=0;272+ #if DIVOPLEN!=4273+ #error Unexpected Quad DIVOPLEN274+ #endif275+ #endif276+277+ // set msu and lsu pointers278+ msua=acc+DIVACCLEN-1; // [leading zeros removed below]279+ msuq=quo+DIVOPLEN;280+ //[loop for div will terminate because operands are non-zero]281+ for (msud=div+DIVOPLEN-1; *msud==0;) msud--;282+ // the initial least-significant unit of acc is set so acc appears283+ // to have the same length as div.284+ // This moves one position towards the least possible for each285+ // iteration286+ divunits=(Int)(msud-div+1); // precalculate287+ lsua=msua-divunits+1; // initial working lsu of acc288+ lsuq=msuq; // and of quo289+290+ // set up the estimator for the multiplier; this is the msu of div,291+ // plus two bits from the unit below (if any) rounded up by one if292+ // there are any non-zero bits or units below that [the extra two293+ // bits makes for a much better estimate when the top unit is small]294+ divtop=*msud<<2;295+ if (divunits>1) {296+ uInt *um=msud-1;297+ uInt d=*um;298+ if (d>=750000000) {divtop+=3; d-=750000000;}299+ else if (d>=500000000) {divtop+=2; d-=500000000;}300+ else if (d>=250000000) {divtop++; d-=250000000;}301+ if (d) divtop++;302+ else for (um--; um>=div; um--) if (*um) {303+ divtop++;304+ break;305+ }306+ } // >1 unit307+308+ #if DECTRACE309+ {Int i;310+ printf("----- div=");311+ for (i=divunits-1; i>=0; i--) printf("%09ld ", (LI)div[i]);312+ printf("\n");}313+ #endif314+315+ // now collect up to DECPMAX+1 digits in the quotient (this may316+ // need OPLEN+1 uInts if unaligned)317+ quodigits=0; // no digits yet318+ for (;; lsua--) { // outer loop -- each input position319+ #if DECCHECK320+ if (lsua<acc) {321+ printf("Acc underrun...\n");322+ break;323+ }324+ #endif325+ #if DECTRACE326+ printf("Outer: quodigits=%ld acc=", (LI)quodigits);327+ for (ua=msua; ua>=lsua; ua--) printf("%09ld ", (LI)*ua);328+ printf("\n");329+ #endif330+ *lsuq=0; // default unit result is 0331+ for (;;) { // inner loop -- calculate quotient unit332+ // strip leading zero units from acc (either there initially or333+ // from subtraction below); this may strip all if exactly 0334+ for (; *msua==0 && msua>=lsua;) msua--;335+ accunits=(Int)(msua-lsua+1); // [maybe 0]336+ // subtraction is only necessary and possible if there are as337+ // least as many units remaining in acc for this iteration as338+ // there are in div339+ if (accunits<divunits) {340+ if (accunits==0) msua++; // restore341+ break;342+ }343+344+ // If acc is longer than div then subtraction is definitely345+ // possible (as msu of both is non-zero), but if they are the346+ // same length a comparison is needed.347+ // If a subtraction is needed then a good estimate of the348+ // multiplier for the subtraction is also needed in order to349+ // minimise the iterations of this inner loop because the350+ // subtractions needed dominate division performance.351+ if (accunits==divunits) {352+ // compare the high divunits of acc and div:353+ // acc<div: this quotient unit is unchanged; subtraction354+ // will be possible on the next iteration355+ // acc==div: quotient gains 1, set acc=0356+ // acc>div: subtraction necessary at this position357+ for (ud=msud, ua=msua; ud>div; ud--, ua--) if (*ud!=*ua) break;358+ // [now at first mismatch or lsu]359+ if (*ud>*ua) break; // next time...360+ if (*ud==*ua) { // all compared equal361+ *lsuq+=1; // increment result362+ msua=lsua; // collapse acc units363+ *msua=0; // .. to a zero364+ break;365+ }366+367+ // subtraction necessary; estimate multiplier [see above]368+ // if both *msud and *msua are small it is cost-effective to369+ // bring in part of the following units (if any) to get a370+ // better estimate (assume some other non-zero in div)371+ #define DIVLO 1000000U372+ #define DIVHI (DIVBASE/DIVLO)373+ #if DECUSE64374+ if (divunits>1) {375+ // there cannot be a *(msud-2) for DECDOUBLE so next is376+ // an exact calculation unless DECQUAD (which needs to377+ // assume bits out there if divunits>2)378+ uLong mul=(uLong)*msua * DIVBASE + *(msua-1);379+ uLong div=(uLong)*msud * DIVBASE + *(msud-1);380+ #if QUAD381+ if (divunits>2) div++;382+ #endif383+ mul/=div;384+ multiplier=(Int)mul;385+ }386+ else multiplier=*msua/(*msud);387+ #else388+ if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {389+ multiplier=(*msua*DIVHI + *(msua-1)/DIVLO)390+ /(*msud*DIVHI + *(msud-1)/DIVLO +1);391+ }392+ else multiplier=(*msua<<2)/divtop;393+ #endif394+ }395+ else { // accunits>divunits396+ // msud is one unit 'lower' than msua, so estimate differently397+ #if DECUSE64398+ uLong mul;399+ // as before, bring in extra digits if possible400+ if (divunits>1 && *msua<DIVLO && *msud<DIVLO) {401+ mul=((uLong)*msua * DIVHI * DIVBASE) + *(msua-1) * DIVHI402+ + *(msua-2)/DIVLO;403+ mul/=(*msud*DIVHI + *(msud-1)/DIVLO +1);404+ }405+ else if (divunits==1) {406+ mul=(uLong)*msua * DIVBASE + *(msua-1);407+ mul/=*msud; // no more to the right408+ }409+ else {410+ mul=(uLong)(*msua) * (uInt)(DIVBASE<<2)411+ + (*(msua-1)<<2);412+ mul/=divtop; // [divtop already allows for sticky bits]413+ }414+ multiplier=(Int)mul;415+ #else416+ multiplier=*msua * ((DIVBASE<<2)/divtop);417+ #endif418+ }419+ if (multiplier==0) multiplier=1; // marginal case420+ *lsuq+=multiplier;421+422+ #if DIVCOUNT423+ // printf("Multiplier: %ld\n", (LI)multiplier);424+ divcount++;425+ #endif426+427+ // Carry out the subtraction acc-(div*multiplier); for each428+ // unit in div, do the multiply, split to units (see429+ // decFloatMultiply for the algorithm), and subtract from acc430+ #define DIVMAGIC 2305843009U // 2**61/10**9431+ #define DIVSHIFTA 29432+ #define DIVSHIFTB 32433+ carry=0;434+ for (ud=div, ua=lsua; ud<=msud; ud++, ua++) {435+ uInt lo, hop;436+ #if DECUSE64437+ uLong sub=(uLong)multiplier*(*ud)+carry;438+ if (sub<DIVBASE) {439+ carry=0;440+ lo=(uInt)sub;441+ }442+ else {443+ hop=(uInt)(sub>>DIVSHIFTA);444+ carry=(uInt)(((uLong)hop*DIVMAGIC)>>DIVSHIFTB);445+ // the estimate is now in hi; now calculate sub-hi*10**9446+ // to get the remainder (which will be <DIVBASE))447+ lo=(uInt)sub;448+ lo-=carry*DIVBASE; // low word of result449+ if (lo>=DIVBASE) {450+ lo-=DIVBASE; // correct by +1451+ carry++;452+ }453+ }454+ #else // 32-bit455+ uInt hi;456+ // calculate multiplier*(*ud) into hi and lo457+ LONGMUL32HI(hi, *ud, multiplier); // get the high word458+ lo=multiplier*(*ud); // .. and the low459+ lo+=carry; // add the old hi460+ carry=hi+(lo<carry); // .. with any carry461+ if (carry || lo>=DIVBASE) { // split is needed462+ hop=(carry<<3)+(lo>>DIVSHIFTA); // hi:lo/2**29463+ LONGMUL32HI(carry, hop, DIVMAGIC); // only need the high word464+ // [DIVSHIFTB is 32, so carry can be used directly]465+ // the estimate is now in carry; now calculate hi:lo-est*10**9;466+ // happily the top word of the result is irrelevant because it467+ // will always be zero so this needs only one multiplication468+ lo-=(carry*DIVBASE);469+ // the correction here will be at most +1; do it470+ if (lo>=DIVBASE) {471+ lo-=DIVBASE;472+ carry++;473+ }474+ }475+ #endif476+ if (lo>*ua) { // borrow needed477+ *ua+=DIVBASE;478+ carry++;479+ }480+ *ua-=lo;481+ } // ud loop482+ if (carry) *ua-=carry; // accdigits>divdigits [cannot borrow]483+ } // inner loop484+485+ // the outer loop terminates when there is either an exact result486+ // or enough digits; first update the quotient digit count and487+ // pointer (if any significant digits)488+ #if DECTRACE489+ if (*lsuq || quodigits) printf("*lsuq=%09ld\n", (LI)*lsuq);490+ #endif491+ if (quodigits) {492+ quodigits+=9; // had leading unit earlier493+ lsuq--;494+ if (quodigits>DECPMAX+1) break; // have enough495+ }496+ else if (*lsuq) { // first quotient digits497+ const uInt *pow;498+ for (pow=DECPOWERS; *lsuq>=*pow; pow++) quodigits++;499+ lsuq--;500+ // [cannot have >DECPMAX+1 on first unit]501+ }502+503+ if (*msua!=0) continue; // not an exact result504+ // acc is zero iff used all of original units and zero down to lsua505+ // (must also continue to original lsu for correct quotient length)506+ if (lsua>acc+DIVACCLEN-DIVOPLEN) continue;507+ for (; msua>lsua && *msua==0;) msua--;508+ if (*msua==0 && msua==lsua) break;509+ } // outer loop510+511+ // all of the original operand in acc has been covered at this point512+ // quotient now has at least DECPMAX+2 digits513+ // *msua is now non-0 if inexact and sticky bits514+ // lsuq is one below the last uint of the quotient515+ lsuq++; // set -> true lsu of quo516+ if (*msua) *lsuq|=1; // apply sticky bit517+518+ // quo now holds the (unrounded) quotient in base-billion; one519+ // base-billion 'digit' per uInt.520+ #if DECTRACE521+ printf("DivQuo:");522+ for (uq=msuq; uq>=lsuq; uq--) printf(" %09ld", (LI)*uq);523+ printf("\n");524+ #endif525+526+ // Now convert to BCD for rounding and cleanup, starting from the527+ // most significant end [offset by one into bcdacc to leave room528+ // for a possible carry digit if rounding for REMNEAR is needed]529+ for (uq=msuq, ub=bcdacc+1; uq>=lsuq; uq--, ub+=9) {530+ uInt top, mid, rem; // work531+ if (*uq==0) { // no split needed532+ UBFROMUI(ub, 0); // clear 9 BCD8s533+ UBFROMUI(ub+4, 0); // ..534+ *(ub+8)=0; // ..535+ continue;536+ }537+ // *uq is non-zero -- split the base-billion digit into538+ // hi, mid, and low three-digits539+ #define divsplit9 1000000 // divisor540+ #define divsplit6 1000 // divisor541+ // The splitting is done by simple divides and remainders,542+ // assuming the compiler will optimize these [GCC does]543+ top=*uq/divsplit9;544+ rem=*uq%divsplit9;545+ mid=rem/divsplit6;546+ rem=rem%divsplit6;547+ // lay out the nine BCD digits (plus one unwanted byte)548+ UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4]));549+ UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));550+ UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));551+ } // BCD conversion loop552+ ub--; // -> lsu553+554+ // complete the bcdnum; quodigits is correct, so the position of555+ // the first non-zero is known556+ num.msd=bcdacc+1+(msuq-lsuq+1)*9-quodigits;557+ num.lsd=ub;558+559+ // make exponent adjustments, etc560+ if (lsua<acc+DIVACCLEN-DIVOPLEN) { // used extra digits561+ num.exponent-=(Int)((acc+DIVACCLEN-DIVOPLEN-lsua)*9);562+ // if the result was exact then there may be up to 8 extra563+ // trailing zeros in the overflowed quotient final unit564+ if (*msua==0) {565+ for (; *ub==0;) ub--; // drop zeros566+ num.exponent+=(Int)(num.lsd-ub); // and adjust exponent567+ num.lsd=ub;568+ }569+ } // adjustment needed570+571+ #if DIVCOUNT572+ if (divcount>maxcount) { // new high-water nark573+ maxcount=divcount;574+ printf("DivNewMaxCount: %ld\n", (LI)maxcount);575+ }576+ #endif577+578+ if (op&DIVIDE) return decFinalize(result, &num, set); // all done579+580+ // Is DIVIDEINT or a remainder; there is more to do -- first form581+ // the integer (this is done 'after the fact', unlike as in582+ // decNumber, so as not to tax DIVIDE)583+584+ // The first non-zero digit will be in the first 9 digits, known585+ // from quodigits and num.msd, so there is always space for DECPMAX586+ // digits587+588+ length=(Int)(num.lsd-num.msd+1);589+ //printf("Length exp: %ld %ld\n", (LI)length, (LI)num.exponent);590+591+ if (length+num.exponent>DECPMAX) { // cannot fit592+ decFloatZero(result);593+ DFWORD(result, 0)=DECFLOAT_qNaN;594+ set->status|=DEC_Division_impossible;595+ return result;596+ }597+598+ if (num.exponent>=0) { // already an int, or need pad zeros599+ for (ub=num.lsd+1; ub<=num.lsd+num.exponent; ub++) *ub=0;600+ num.lsd+=num.exponent;601+ }602+ else { // too long: round or truncate needed603+ Int drop=-num.exponent;604+ if (!(op&REMNEAR)) { // simple truncate605+ num.lsd-=drop;606+ if (num.lsd<num.msd) { // truncated all607+ num.lsd=num.msd; // make 0608+ *num.lsd=0; // .. [sign still relevant]609+ }610+ }611+ else { // round to nearest even [sigh]612+ // round-to-nearest, in-place; msd is at or to right of bcdacc+1613+ // (this is a special case of Quantize -- q.v. for commentary)614+ uByte *roundat; // -> re-round digit615+ uByte reround; // reround value616+ *(num.msd-1)=0; // in case of left carry, or make 0617+ if (drop<length) roundat=num.lsd-drop+1;618+ else if (drop==length) roundat=num.msd;619+ else roundat=num.msd-1; // [-> 0]620+ reround=*roundat;621+ for (ub=roundat+1; ub<=num.lsd; ub++) {622+ if (*ub!=0) {623+ reround=DECSTICKYTAB[reround];624+ break;625+ }626+ } // check stickies627+ if (roundat>num.msd) num.lsd=roundat-1;628+ else {629+ num.msd--; // use the 0 ..630+ num.lsd=num.msd; // .. at the new MSD place631+ }632+ if (reround!=0) { // discarding non-zero633+ uInt bump=0;634+ // rounding is DEC_ROUND_HALF_EVEN always635+ if (reround>5) bump=1; // >0.5 goes up636+ else if (reround==5) // exactly 0.5000 ..637+ bump=*(num.lsd) & 0x01; // .. up iff [new] lsd is odd638+ if (bump!=0) { // need increment639+ // increment the coefficient; this might end up with 1000...640+ ub=num.lsd;641+ for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);642+ for (; *ub==9; ub--) *ub=0; // at most 3 more643+ *ub+=1;644+ if (ub<num.msd) num.msd--; // carried645+ } // bump needed646+ } // reround!=0647+ } // remnear648+ } // round or truncate needed649+ num.exponent=0; // all paths650+ //decShowNum(&num, "int");651+652+ if (op&DIVIDEINT) return decFinalize(result, &num, set); // all done653+654+ // Have a remainder to calculate655+ decFinalize("ient, &num, set); // lay out the integer so far656+ DFWORD("ient, 0)^=DECFLOAT_Sign; // negate it657+ sign=DFWORD(dfl, 0); // save sign of dfl658+ decFloatFMA(result, "ient, dfr, dfl, set);659+ if (!DFISZERO(result)) return result;660+ // if the result is zero the sign shall be sign of dfl661+ DFWORD("ient, 0)=sign; // construct decFloat of sign662+ return decFloatCopySign(result, result, "ient);663+ } // decDivide664+665+/* ------------------------------------------------------------------ */666+/* decFiniteMultiply -- multiply two finite decFloats */667+/* */668+/* num gets the result of multiplying dfl and dfr */669+/* bcdacc .. with the coefficient in this array */670+/* dfl is the first decFloat (lhs) */671+/* dfr is the second decFloat (rhs) */672+/* */673+/* This effects the multiplication of two decFloats, both known to be */674+/* finite, leaving the result in a bcdnum ready for decFinalize (for */675+/* use in Multiply) or in a following addition (FMA). */676+/* */677+/* bcdacc must have space for at least DECPMAX9*18+1 bytes. */678+/* No error is possible and no status is set. */679+/* ------------------------------------------------------------------ */680+// This routine has two separate implementations of the core681+// multiplication; both using base-billion. One uses only 32-bit682+// variables (Ints and uInts) or smaller; the other uses uLongs (for683+// multiplication and addition only). Both implementations cover684+// both arithmetic sizes (DOUBLE and QUAD) in order to allow timing685+// comparisons. In any one compilation only one implementation for686+// each size can be used, and if DECUSE64 is 0 then use of the 32-bit687+// version is forced.688+//689+// Historical note: an earlier version of this code also supported the690+// 256-bit format and has been preserved. That is somewhat trickier691+// during lazy carry splitting because the initial quotient estimate692+// (est) can exceed 32 bits.693+694+#define MULTBASE ((uInt)BILLION) // the base used for multiply695+#define MULOPLEN DECPMAX9 // operand length ('digits' base 10**9)696+#define MULACCLEN (MULOPLEN*2) // accumulator length (ditto)697+#define LEADZEROS (MULACCLEN*9 - DECPMAX*2) // leading zeros always698+699+// Assertions: exponent not too large and MULACCLEN is a multiple of 4700+#if DECEMAXD>9701+ #error Exponent may overflow when doubled for Multiply702+#endif703+#if MULACCLEN!=(MULACCLEN/4)*4704+ // This assumption is used below only for initialization705+ #error MULACCLEN is not a multiple of 4706+#endif707+708+static void decFiniteMultiply(bcdnum *num, uByte *bcdacc,709+ const decFloat *dfl, const decFloat *dfr) {710+ uInt bufl[MULOPLEN]; // left coefficient (base-billion)711+ uInt bufr[MULOPLEN]; // right coefficient (base-billion)712+ uInt *ui, *uj; // work713+ uByte *ub; // ..714+ uInt uiwork; // for macros715+716+ #if DECUSE64717+ uLong accl[MULACCLEN]; // lazy accumulator (base-billion+)718+ uLong *pl; // work -> lazy accumulator719+ uInt acc[MULACCLEN]; // coefficent in base-billion ..720+ #else721+ uInt acc[MULACCLEN*2]; // accumulator in base-billion ..722+ #endif723+ uInt *pa; // work -> accumulator724+ //printf("Base10**9: OpLen=%d MulAcclen=%d\n", OPLEN, MULACCLEN);725+726+ /* Calculate sign and exponent */727+ num->sign=(DFWORD(dfl, 0)^DFWORD(dfr, 0)) & DECFLOAT_Sign;728+ num->exponent=GETEXPUN(dfl)+GETEXPUN(dfr); // [see assertion above]729+730+ /* Extract the coefficients and prepare the accumulator */731+ // the coefficients of the operands are decoded into base-billion732+ // numbers in uInt arrays (bufl and bufr, LSD at offset 0) of the733+ // appropriate size.734+ GETCOEFFBILL(dfl, bufl);735+ GETCOEFFBILL(dfr, bufr);736+ #if DECTRACE && 0737+ printf("CoeffbL:");738+ for (ui=bufl+MULOPLEN-1; ui>=bufl; ui--) printf(" %08lx", (LI)*ui);739+ printf("\n");740+ printf("CoeffbR:");741+ for (uj=bufr+MULOPLEN-1; uj>=bufr; uj--) printf(" %08lx", (LI)*uj);742+ printf("\n");743+ #endif744+745+ // start the 64-bit/32-bit differing paths...746+#if DECUSE64747+748+ // zero the accumulator749+ #if MULACCLEN==4750+ accl[0]=0; accl[1]=0; accl[2]=0; accl[3]=0;751+ #else // use a loop752+ // MULACCLEN is a multiple of four, asserted above753+ for (pl=accl; pl<accl+MULACCLEN; pl+=4) {754+ *pl=0; *(pl+1)=0; *(pl+2)=0; *(pl+3)=0;// [reduce overhead]755+ } // pl756+ #endif757+758+ /* Effect the multiplication */759+ // The multiplcation proceeds using MFC's lazy-carry resolution760+ // algorithm from decNumber. First, the multiplication is761+ // effected, allowing accumulation of the partial products (which762+ // are in base-billion at each column position) into 64 bits763+ // without resolving back to base=billion after each addition.764+ // These 64-bit numbers (which may contain up to 19 decimal digits)765+ // are then split using the Clark & Cowlishaw algorithm (see below).766+ // [Testing for 0 in the inner loop is not really a 'win']767+ for (ui=bufr; ui<bufr+MULOPLEN; ui++) { // over each item in rhs768+ if (*ui==0) continue; // product cannot affect result769+ pl=accl+(ui-bufr); // where to add the lhs770+ for (uj=bufl; uj<bufl+MULOPLEN; uj++, pl++) { // over each item in lhs771+ // if (*uj==0) continue; // product cannot affect result772+ *pl+=((uLong)*ui)*(*uj);773+ } // uj774+ } // ui775+776+ // The 64-bit carries must now be resolved; this means that a777+ // quotient/remainder has to be calculated for base-billion (1E+9).778+ // For this, Clark & Cowlishaw's quotient estimation approach (also779+ // used in decNumber) is needed, because 64-bit divide is generally780+ // extremely slow on 32-bit machines, and may be slower than this781+ // approach even on 64-bit machines. This algorithm splits X782+ // using:783+ //784+ // magic=2**(A+B)/1E+9; // 'magic number'785+ // hop=X/2**A; // high order part of X (by shift)786+ // est=magic*hop/2**B // quotient estimate (may be low by 1)787+ //788+ // A and B are quite constrained; hop and magic must fit in 32 bits,789+ // and 2**(A+B) must be as large as possible (which is 2**61 if790+ // magic is to fit). Further, maxX increases with the length of791+ // the operands (and hence the number of partial products792+ // accumulated); maxX is OPLEN*(10**18), which is up to 19 digits.793+ //794+ // It can be shown that when OPLEN is 2 then the maximum error in795+ // the estimated quotient is <1, but for larger maximum x the796+ // maximum error is above 1 so a correction that is >1 may be797+ // needed. Values of A and B are chosen to satisfy the constraints798+ // just mentioned while minimizing the maximum error (and hence the799+ // maximum correction), as shown in the following table:800+ //801+ // Type OPLEN A B maxX maxError maxCorrection802+ // ---------------------------------------------------------803+ // DOUBLE 2 29 32 <2*10**18 0.63 1804+ // QUAD 4 30 31 <4*10**18 1.17 2805+ //806+ // In the OPLEN==2 case there is most choice, but the value for B807+ // of 32 has a big advantage as then the calculation of the808+ // estimate requires no shifting; the compiler can extract the high809+ // word directly after multiplying magic*hop.810+ #define MULMAGIC 2305843009U // 2**61/10**9 [both cases]811+ #if DOUBLE812+ #define MULSHIFTA 29813+ #define MULSHIFTB 32814+ #elif QUAD815+ #define MULSHIFTA 30816+ #define MULSHIFTB 31817+ #else818+ #error Unexpected type819+ #endif820+821+ #if DECTRACE822+ printf("MulAccl:");823+ for (pl=accl+MULACCLEN-1; pl>=accl; pl--)824+ printf(" %08lx:%08lx", (LI)(*pl>>32), (LI)(*pl&0xffffffff));825+ printf("\n");826+ #endif827+828+ for (pl=accl, pa=acc; pl<accl+MULACCLEN; pl++, pa++) { // each column position829+ uInt lo, hop; // work830+ uInt est; // cannot exceed 4E+9831+ if (*pl>=MULTBASE) {832+ // *pl holds a binary number which needs to be split833+ hop=(uInt)(*pl>>MULSHIFTA);834+ est=(uInt)(((uLong)hop*MULMAGIC)>>MULSHIFTB);835+ // the estimate is now in est; now calculate hi:lo-est*10**9;836+ // happily the top word of the result is irrelevant because it837+ // will always be zero so this needs only one multiplication838+ lo=(uInt)(*pl-((uLong)est*MULTBASE)); // low word of result839+ // If QUAD, the correction here could be +2840+ if (lo>=MULTBASE) {841+ lo-=MULTBASE; // correct by +1842+ est++;843+ #if QUAD844+ // may need to correct by +2845+ if (lo>=MULTBASE) {846+ lo-=MULTBASE;847+ est++;848+ }849+ #endif850+ }851+ // finally place lo as the new coefficient 'digit' and add est to852+ // the next place up [this is safe because this path is never853+ // taken on the final iteration as *pl will fit]854+ *pa=lo;855+ *(pl+1)+=est;856+ } // *pl needed split857+ else { // *pl<MULTBASE858+ *pa=(uInt)*pl; // just copy across859+ }860+ } // pl loop861+862+#else // 32-bit863+ for (pa=acc;; pa+=4) { // zero the accumulator864+ *pa=0; *(pa+1)=0; *(pa+2)=0; *(pa+3)=0; // [reduce overhead]865+ if (pa==acc+MULACCLEN*2-4) break; // multiple of 4 asserted866+ } // pa867+868+ /* Effect the multiplication */869+ // uLongs are not available (and in particular, there is no uLong870+ // divide) but it is still possible to use MFC's lazy-carry871+ // resolution algorithm from decNumber. First, the multiplication872+ // is effected, allowing accumulation of the partial products873+ // (which are in base-billion at each column position) into 64 bits874+ // [with the high-order 32 bits in each position being held at875+ // offset +ACCLEN from the low-order 32 bits in the accumulator].876+ // These 64-bit numbers (which may contain up to 19 decimal digits)877+ // are then split using the Clark & Cowlishaw algorithm (see878+ // below).879+ for (ui=bufr;; ui++) { // over each item in rhs880+ uInt hi, lo; // words of exact multiply result881+ pa=acc+(ui-bufr); // where to add the lhs882+ for (uj=bufl;; uj++, pa++) { // over each item in lhs883+ LONGMUL32HI(hi, *ui, *uj); // calculate product of digits884+ lo=(*ui)*(*uj); // ..885+ *pa+=lo; // accumulate low bits and ..886+ *(pa+MULACCLEN)+=hi+(*pa<lo); // .. high bits with any carry887+ if (uj==bufl+MULOPLEN-1) break;888+ }889+ if (ui==bufr+MULOPLEN-1) break;890+ }891+892+ // The 64-bit carries must now be resolved; this means that a893+ // quotient/remainder has to be calculated for base-billion (1E+9).894+ // For this, Clark & Cowlishaw's quotient estimation approach (also895+ // used in decNumber) is needed, because 64-bit divide is generally896+ // extremely slow on 32-bit machines. This algorithm splits X897+ // using:898+ //899+ // magic=2**(A+B)/1E+9; // 'magic number'900+ // hop=X/2**A; // high order part of X (by shift)901+ // est=magic*hop/2**B // quotient estimate (may be low by 1)902+ //903+ // A and B are quite constrained; hop and magic must fit in 32 bits,904+ // and 2**(A+B) must be as large as possible (which is 2**61 if905+ // magic is to fit). Further, maxX increases with the length of906+ // the operands (and hence the number of partial products907+ // accumulated); maxX is OPLEN*(10**18), which is up to 19 digits.908+ //909+ // It can be shown that when OPLEN is 2 then the maximum error in910+ // the estimated quotient is <1, but for larger maximum x the911+ // maximum error is above 1 so a correction that is >1 may be912+ // needed. Values of A and B are chosen to satisfy the constraints913+ // just mentioned while minimizing the maximum error (and hence the914+ // maximum correction), as shown in the following table:915+ //916+ // Type OPLEN A B maxX maxError maxCorrection917+ // ---------------------------------------------------------918+ // DOUBLE 2 29 32 <2*10**18 0.63 1919+ // QUAD 4 30 31 <4*10**18 1.17 2920+ //921+ // In the OPLEN==2 case there is most choice, but the value for B922+ // of 32 has a big advantage as then the calculation of the923+ // estimate requires no shifting; the high word is simply924+ // calculated from multiplying magic*hop.925+ #define MULMAGIC 2305843009U // 2**61/10**9 [both cases]926+ #if DOUBLE927+ #define MULSHIFTA 29928+ #define MULSHIFTB 32929+ #elif QUAD930+ #define MULSHIFTA 30931+ #define MULSHIFTB 31932+ #else933+ #error Unexpected type934+ #endif935+936+ #if DECTRACE937+ printf("MulHiLo:");938+ for (pa=acc+MULACCLEN-1; pa>=acc; pa--)939+ printf(" %08lx:%08lx", (LI)*(pa+MULACCLEN), (LI)*pa);940+ printf("\n");941+ #endif942+943+ for (pa=acc;; pa++) { // each low uInt944+ uInt hi, lo; // words of exact multiply result945+ uInt hop, estlo; // work946+ #if QUAD947+ uInt esthi; // ..948+ #endif949+950+ lo=*pa;951+ hi=*(pa+MULACCLEN); // top 32 bits952+ // hi and lo now hold a binary number which needs to be split953+954+ #if DOUBLE955+ hop=(hi<<3)+(lo>>MULSHIFTA); // hi:lo/2**29956+ LONGMUL32HI(estlo, hop, MULMAGIC);// only need the high word957+ // [MULSHIFTB is 32, so estlo can be used directly]958+ // the estimate is now in estlo; now calculate hi:lo-est*10**9;959+ // happily the top word of the result is irrelevant because it960+ // will always be zero so this needs only one multiplication961+ lo-=(estlo*MULTBASE);962+ // esthi=0; // high word is ignored below963+ // the correction here will be at most +1; do it964+ if (lo>=MULTBASE) {965+ lo-=MULTBASE;966+ estlo++;967+ }968+ #elif QUAD969+ hop=(hi<<2)+(lo>>MULSHIFTA); // hi:lo/2**30970+ LONGMUL32HI(esthi, hop, MULMAGIC);// shift will be 31 ..971+ estlo=hop*MULMAGIC; // .. so low word needed972+ estlo=(esthi<<1)+(estlo>>MULSHIFTB); // [just the top bit]973+ // esthi=0; // high word is ignored below974+ lo-=(estlo*MULTBASE); // as above975+ // the correction here could be +1 or +2976+ if (lo>=MULTBASE) {977+ lo-=MULTBASE;978+ estlo++;979+ }980+ if (lo>=MULTBASE) {981+ lo-=MULTBASE;982+ estlo++;983+ }984+ #else985+ #error Unexpected type986+ #endif987+988+ // finally place lo as the new accumulator digit and add est to989+ // the next place up; this latter add could cause a carry of 1990+ // to the high word of the next place991+ *pa=lo;992+ *(pa+1)+=estlo;993+ // esthi is always 0 for DOUBLE and QUAD so this is skipped994+ // *(pa+1+MULACCLEN)+=esthi;995+ if (*(pa+1)<estlo) *(pa+1+MULACCLEN)+=1; // carry996+ if (pa==acc+MULACCLEN-2) break; // [MULACCLEN-1 will never need split]997+ } // pa loop998+#endif999+1000+ // At this point, whether using the 64-bit or the 32-bit paths, the1001+ // accumulator now holds the (unrounded) result in base-billion;1002+ // one base-billion 'digit' per uInt.1003+ #if DECTRACE1004+ printf("MultAcc:");1005+ for (pa=acc+MULACCLEN-1; pa>=acc; pa--) printf(" %09ld", (LI)*pa);1006+ printf("\n");1007+ #endif1008+1009+ // Now convert to BCD for rounding and cleanup, starting from the1010+ // most significant end1011+ pa=acc+MULACCLEN-1;1012+ if (*pa!=0) num->msd=bcdacc+LEADZEROS;// drop known lead zeros1013+ else { // >=1 word of leading zeros1014+ num->msd=bcdacc; // known leading zeros are gone1015+ pa--; // skip first word ..1016+ for (; *pa==0; pa--) if (pa==acc) break; // .. and any more leading 0s1017+ }1018+ for (ub=bcdacc;; pa--, ub+=9) {1019+ if (*pa!=0) { // split(s) needed1020+ uInt top, mid, rem; // work1021+ // *pa is non-zero -- split the base-billion acc digit into1022+ // hi, mid, and low three-digits1023+ #define mulsplit9 1000000 // divisor1024+ #define mulsplit6 1000 // divisor1025+ // The splitting is done by simple divides and remainders,1026+ // assuming the compiler will optimize these where useful1027+ // [GCC does]1028+ top=*pa/mulsplit9;1029+ rem=*pa%mulsplit9;1030+ mid=rem/mulsplit6;1031+ rem=rem%mulsplit6;1032+ // lay out the nine BCD digits (plus one unwanted byte)1033+ UBFROMUI(ub, UBTOUI(&BIN2BCD8[top*4]));1034+ UBFROMUI(ub+3, UBTOUI(&BIN2BCD8[mid*4]));1035+ UBFROMUI(ub+6, UBTOUI(&BIN2BCD8[rem*4]));1036+ }1037+ else { // *pa==01038+ UBFROMUI(ub, 0); // clear 9 BCD8s1039+ UBFROMUI(ub+4, 0); // ..1040+ *(ub+8)=0; // ..1041+ }1042+ if (pa==acc) break;1043+ } // BCD conversion loop1044+1045+ num->lsd=ub+8; // complete the bcdnum ..1046+1047+ #if DECTRACE1048+ decShowNum(num, "postmult");1049+ decFloatShow(dfl, "dfl");1050+ decFloatShow(dfr, "dfr");1051+ #endif1052+ return;1053+ } // decFiniteMultiply1054+1055+/* ------------------------------------------------------------------ */1056+/* decFloatAbs -- absolute value, heeding NaNs, etc. */1057+/* */1058+/* result gets the canonicalized df with sign 0 */1059+/* df is the decFloat to abs */1060+/* set is the context */1061+/* returns result */1062+/* */1063+/* This has the same effect as decFloatPlus unless df is negative, */1064+/* in which case it has the same effect as decFloatMinus. The */1065+/* effect is also the same as decFloatCopyAbs except that NaNs are */1066+/* handled normally (the sign of a NaN is not affected, and an sNaN */1067+/* will signal) and the result will be canonical. */1068+/* ------------------------------------------------------------------ */1069+decFloat * decFloatAbs(decFloat *result, const decFloat *df,1070+ decContext *set) {1071+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set);1072+ decCanonical(result, df); // copy and check1073+ DFBYTE(result, 0)&=~0x80; // zero sign bit1074+ return result;1075+ } // decFloatAbs1076+1077+/* ------------------------------------------------------------------ */1078+/* decFloatAdd -- add two decFloats */1079+/* */1080+/* result gets the result of adding dfl and dfr: */1081+/* dfl is the first decFloat (lhs) */1082+/* dfr is the second decFloat (rhs) */1083+/* set is the context */1084+/* returns result */1085+/* */1086+/* ------------------------------------------------------------------ */1087+#if QUAD1088+// Table for testing MSDs for fastpath elimination; returns the MSD of1089+// a decDouble or decQuad (top 6 bits tested) ignoring the sign.1090+// Infinities return -32 and NaNs return -128 so that summing the two1091+// MSDs also allows rapid tests for the Specials (see code below).1092+const Int DECTESTMSD[64]={1093+ 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,1094+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128,1095+ 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,1096+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, -32, -128};1097+#else1098+// The table for testing MSDs is shared between the modules1099+extern const Int DECTESTMSD[64];1100+#endif1101+1102+decFloat * decFloatAdd(decFloat *result,1103+ const decFloat *dfl, const decFloat *dfr,1104+ decContext *set) {1105+ bcdnum num; // for final conversion1106+ Int bexpl, bexpr; // left and right biased exponents1107+ uByte *ub, *us, *ut; // work1108+ uInt uiwork; // for macros1109+ #if QUAD1110+ uShort uswork; // ..1111+ #endif1112+1113+ uInt sourhil, sourhir; // top words from source decFloats1114+ // [valid only through end of1115+ // fastpath code -- before swap]1116+ uInt diffsign; // non-zero if signs differ1117+ uInt carry; // carry: 0 or 1 before add loop1118+ Int overlap; // coefficient overlap (if full)1119+ Int summ; // sum of the MSDs1120+ // the following buffers hold coefficients with various alignments1121+ // (see commentary and diagrams below)1122+ uByte acc[4+2+DECPMAX*3+8];1123+ uByte buf[4+2+DECPMAX*2];1124+ uByte *umsd, *ulsd; // local MSD and LSD pointers1125+1126+ #if DECLITEND1127+ #define CARRYPAT 0x01000000 // carry=1 pattern1128+ #else1129+ #define CARRYPAT 0x00000001 // carry=1 pattern1130+ #endif1131+1132+ /* Start decoding the arguments */1133+ // The initial exponents are placed into the opposite Ints to1134+ // that which might be expected; there are two sets of data to1135+ // keep track of (each decFloat and the corresponding exponent),1136+ // and this scheme means that at the swap point (after comparing1137+ // exponents) only one pair of words needs to be swapped1138+ // whichever path is taken (thereby minimising worst-case path).1139+ // The calculated exponents will be nonsense when the arguments are1140+ // Special, but are not used in that path1141+ sourhil=DFWORD(dfl, 0); // LHS top word1142+ summ=DECTESTMSD[sourhil>>26]; // get first MSD for testing1143+ bexpr=DECCOMBEXP[sourhil>>26]; // get exponent high bits (in place)1144+ bexpr+=GETECON(dfl); // .. + continuation1145+1146+ sourhir=DFWORD(dfr, 0); // RHS top word1147+ summ+=DECTESTMSD[sourhir>>26]; // sum MSDs for testing1148+ bexpl=DECCOMBEXP[sourhir>>26];1149+ bexpl+=GETECON(dfr);1150+1151+ // here bexpr has biased exponent from lhs, and vice versa1152+1153+ diffsign=(sourhil^sourhir)&DECFLOAT_Sign;1154+1155+ // now determine whether to take a fast path or the full-function1156+ // slow path. The slow path must be taken when:1157+ // -- both numbers are finite, and:1158+ // the exponents are different, or1159+ // the signs are different, or1160+ // the sum of the MSDs is >8 (hence might overflow)1161+ // specialness and the sum of the MSDs can be tested at once using1162+ // the summ value just calculated, so the test for specials is no1163+ // longer on the worst-case path (as of 3.60)1164+1165+ if (summ<=8) { // MSD+MSD is good, or there is a special1166+ if (summ<0) { // there is a special1167+ // Inf+Inf would give -64; Inf+finite is -32 or higher1168+ if (summ<-64) return decNaNs(result, dfl, dfr, set); // one or two NaNs1169+ // two infinities with different signs is invalid1170+ if (summ==-64 && diffsign) return decInvalid(result, set);1171+ if (DFISINF(dfl)) return decInfinity(result, dfl); // LHS is infinite1172+ return decInfinity(result, dfr); // RHS must be Inf1173+ }1174+ // Here when both arguments are finite; fast path is possible1175+ // (currently only for aligned and same-sign)1176+ if (bexpr==bexpl && !diffsign) {1177+ uInt tac[DECLETS+1]; // base-1000 coefficient1178+ uInt encode; // work1179+1180+ // Get one coefficient as base-1000 and add the other1181+ GETCOEFFTHOU(dfl, tac); // least-significant goes to [0]1182+ ADDCOEFFTHOU(dfr, tac);1183+ // here the sum of the MSDs (plus any carry) will be <10 due to1184+ // the fastpath test earlier1185+1186+ // construct the result; low word is the same for both formats1187+ encode =BIN2DPD[tac[0]];1188+ encode|=BIN2DPD[tac[1]]<<10;1189+ encode|=BIN2DPD[tac[2]]<<20;1190+ encode|=BIN2DPD[tac[3]]<<30;1191+ DFWORD(result, (DECBYTES/4)-1)=encode;1192+1193+ // collect next two declets (all that remains, for Double)1194+ encode =BIN2DPD[tac[3]]>>2;1195+ encode|=BIN2DPD[tac[4]]<<8;1196+1197+ #if QUAD1198+ // complete and lay out middling words1199+ encode|=BIN2DPD[tac[5]]<<18;1200+ encode|=BIN2DPD[tac[6]]<<28;1201+ DFWORD(result, 2)=encode;1202+1203+ encode =BIN2DPD[tac[6]]>>4;1204+ encode|=BIN2DPD[tac[7]]<<6;1205+ encode|=BIN2DPD[tac[8]]<<16;1206+ encode|=BIN2DPD[tac[9]]<<26;1207+ DFWORD(result, 1)=encode;1208+1209+ // and final two declets1210+ encode =BIN2DPD[tac[9]]>>6;1211+ encode|=BIN2DPD[tac[10]]<<4;1212+ #endif1213+1214+ // add exponent continuation and sign (from either argument)1215+ encode|=sourhil & (ECONMASK | DECFLOAT_Sign);1216+1217+ // create lookup index = MSD + top two bits of biased exponent <<41218+ tac[DECLETS]|=(bexpl>>DECECONL)<<4;1219+ encode|=DECCOMBFROM[tac[DECLETS]]; // add constructed combination field1220+ DFWORD(result, 0)=encode; // complete1221+1222+ // decFloatShow(result, ">");1223+ return result;1224+ } // fast path OK1225+ // drop through to slow path1226+ } // low sum or Special(s)1227+1228+ /* Slow path required -- arguments are finite and might overflow, */1229+ /* or require alignment, or might have different signs */1230+1231+ // now swap either exponents or argument pointers1232+ if (bexpl<=bexpr) {1233+ // original left is bigger1234+ Int bexpswap=bexpl;1235+ bexpl=bexpr;1236+ bexpr=bexpswap;1237+ // printf("left bigger\n");1238+ }1239+ else {1240+ const decFloat *dfswap=dfl;1241+ dfl=dfr;1242+ dfr=dfswap;1243+ // printf("right bigger\n");1244+ }1245+ // [here dfl and bexpl refer to the datum with the larger exponent,1246+ // of if the exponents are equal then the original LHS argument]1247+1248+ // if lhs is zero then result will be the rhs (now known to have1249+ // the smaller exponent), which also may need to be tested for zero1250+ // for the weird IEEE 754 sign rules1251+ if (DFISZERO(dfl)) {1252+ decCanonical(result, dfr); // clean copy1253+ // "When the sum of two operands with opposite signs is1254+ // exactly zero, the sign of that sum shall be '+' in all1255+ // rounding modes except round toward -Infinity, in which1256+ // mode that sign shall be '-'."1257+ if (diffsign && DFISZERO(result)) {1258+ DFWORD(result, 0)&=~DECFLOAT_Sign; // assume sign 01259+ if (set->round==DEC_ROUND_FLOOR) DFWORD(result, 0)|=DECFLOAT_Sign;1260+ }1261+ return result;1262+ } // numfl is zero1263+ // [here, LHS is non-zero; code below assumes that]1264+1265+ // Coefficients layout during the calculations to follow:1266+ //1267+ // Overlap case:1268+ // +------------------------------------------------+1269+ // acc: |0000| coeffa | tail B | |1270+ // +------------------------------------------------+1271+ // buf: |0000| pad0s | coeffb | |1272+ // +------------------------------------------------+1273+ //1274+ // Touching coefficients or gap:1275+ // +------------------------------------------------+1276+ // acc: |0000| coeffa | gap | coeffb |1277+ // +------------------------------------------------+1278+ // [buf not used or needed; gap clamped to Pmax]1279+1280+ // lay out lhs coefficient into accumulator; this starts at acc+41281+ // for decDouble or acc+6 for decQuad so the LSD is word-1282+ // aligned; the top word gap is there only in case a carry digit1283+ // is prefixed after the add -- it does not need to be zeroed1284+ #if DOUBLE1285+ #define COFF 4 // offset into acc1286+ #elif QUAD1287+ UBFROMUS(acc+4, 0); // prefix 001288+ #define COFF 6 // offset into acc1289+ #endif1290+1291+ GETCOEFF(dfl, acc+COFF); // decode from decFloat1292+ ulsd=acc+COFF+DECPMAX-1;1293+ umsd=acc+4; // [having this here avoids1294+1295+ #if DECTRACE1296+ {bcdnum tum;1297+ tum.msd=umsd;1298+ tum.lsd=ulsd;1299+ tum.exponent=bexpl-DECBIAS;1300+ tum.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;1301+ decShowNum(&tum, "dflx");}1302+ #endif1303+1304+ // if signs differ, take ten's complement of lhs (here the1305+ // coefficient is subtracted from all-nines; the 1 is added during1306+ // the later add cycle -- zeros to the right do not matter because1307+ // the complement of zero is zero); these are fixed-length inverts1308+ // where the lsd is known to be at a 4-byte boundary (so no borrow1309+ // possible)1310+ carry=0; // assume no carry1311+ if (diffsign) {1312+ carry=CARRYPAT; // for +1 during add1313+ UBFROMUI(acc+ 4, 0x09090909-UBTOUI(acc+ 4));1314+ UBFROMUI(acc+ 8, 0x09090909-UBTOUI(acc+ 8));1315+ UBFROMUI(acc+12, 0x09090909-UBTOUI(acc+12));1316+ UBFROMUI(acc+16, 0x09090909-UBTOUI(acc+16));1317+ #if QUAD1318+ UBFROMUI(acc+20, 0x09090909-UBTOUI(acc+20));1319+ UBFROMUI(acc+24, 0x09090909-UBTOUI(acc+24));1320+ UBFROMUI(acc+28, 0x09090909-UBTOUI(acc+28));1321+ UBFROMUI(acc+32, 0x09090909-UBTOUI(acc+32));1322+ UBFROMUI(acc+36, 0x09090909-UBTOUI(acc+36));1323+ #endif1324+ } // diffsign1325+1326+ // now process the rhs coefficient; if it cannot overlap lhs then1327+ // it can be put straight into acc (with an appropriate gap, if1328+ // needed) because no actual addition will be needed (except1329+ // possibly to complete ten's complement)1330+ overlap=DECPMAX-(bexpl-bexpr);1331+ #if DECTRACE1332+ printf("exps: %ld %ld\n", (LI)(bexpl-DECBIAS), (LI)(bexpr-DECBIAS));1333+ printf("Overlap=%ld carry=%08lx\n", (LI)overlap, (LI)carry);1334+ #endif1335+1336+ if (overlap<=0) { // no overlap possible1337+ uInt gap; // local work1338+ // since a full addition is not needed, a ten's complement1339+ // calculation started above may need to be completed1340+ if (carry) {1341+ for (ub=ulsd; *ub==9; ub--) *ub=0;1342+ *ub+=1;1343+ carry=0; // taken care of1344+ }1345+ // up to DECPMAX-1 digits of the final result can extend down1346+ // below the LSD of the lhs, so if the gap is >DECPMAX then the1347+ // rhs will be simply sticky bits. In this case the gap is1348+ // clamped to DECPMAX and the exponent adjusted to suit [this is1349+ // safe because the lhs is non-zero].1350+ gap=-overlap;1351+ if (gap>DECPMAX) {1352+ bexpr+=gap-1;1353+ gap=DECPMAX;1354+ }1355+ ub=ulsd+gap+1; // where MSD will go1356+ // Fill the gap with 0s; note that there is no addition to do1357+ ut=acc+COFF+DECPMAX; // start of gap1358+ for (; ut<ub; ut+=4) UBFROMUI(ut, 0); // mind the gap1359+ if (overlap<-DECPMAX) { // gap was > DECPMAX1360+ *ub=(uByte)(!DFISZERO(dfr)); // make sticky digit1361+ }1362+ else { // need full coefficient1363+ GETCOEFF(dfr, ub); // decode from decFloat1364+ ub+=DECPMAX-1; // new LSD...1365+ }1366+ ulsd=ub; // save new LSD1367+ } // no overlap possible1368+1369+ else { // overlap>01370+ // coefficients overlap (perhaps completely, although also1371+ // perhaps only where zeros)1372+ if (overlap==DECPMAX) { // aligned1373+ ub=buf+COFF; // where msd will go1374+ #if QUAD1375+ UBFROMUS(buf+4, 0); // clear quad's 001376+ #endif1377+ GETCOEFF(dfr, ub); // decode from decFloat1378+ }1379+ else { // unaligned1380+ ub=buf+COFF+DECPMAX-overlap; // where MSD will go1381+ // Fill the prefix gap with 0s; 8 will cover most common1382+ // unalignments, so start with direct assignments (a loop is1383+ // then used for any remaining -- the loop (and the one in a1384+ // moment) is not then on the critical path because the number1385+ // of additions is reduced by (at least) two in this case)1386+ UBFROMUI(buf+4, 0); // [clears decQuad 00 too]1387+ UBFROMUI(buf+8, 0);1388+ if (ub>buf+12) {1389+ ut=buf+12; // start any remaining1390+ for (; ut<ub; ut+=4) UBFROMUI(ut, 0); // fill them1391+ }1392+ GETCOEFF(dfr, ub); // decode from decFloat1393+1394+ // now move tail of rhs across to main acc; again use direct1395+ // copies for 8 digits-worth1396+ UBFROMUI(acc+COFF+DECPMAX, UBTOUI(buf+COFF+DECPMAX));1397+ UBFROMUI(acc+COFF+DECPMAX+4, UBTOUI(buf+COFF+DECPMAX+4));1398+ if (buf+COFF+DECPMAX+8<ub+DECPMAX) {1399+ us=buf+COFF+DECPMAX+8; // source1400+ ut=acc+COFF+DECPMAX+8; // target1401+ for (; us<ub+DECPMAX; us+=4, ut+=4) UBFROMUI(ut, UBTOUI(us));1402+ }1403+ } // unaligned1404+1405+ ulsd=acc+(ub-buf+DECPMAX-1); // update LSD pointer1406+1407+ // Now do the add of the non-tail; this is all nicely aligned,1408+ // and is over a multiple of four digits (because for Quad two1409+ // zero digits were added on the left); words in both acc and1410+ // buf (buf especially) will often be zero1411+ // [byte-by-byte add, here, is about 15% slower total effect than1412+ // the by-fours]1413+1414+ // Now effect the add; this is harder on a little-endian1415+ // machine as the inter-digit carry cannot use the usual BCD1416+ // addition trick because the bytes are loaded in the wrong order1417+ // [this loop could be unrolled, but probably scarcely worth it]1418+1419+ ut=acc+COFF+DECPMAX-4; // target LSW (acc)1420+ us=buf+COFF+DECPMAX-4; // source LSW (buf, to add to acc)1421+1422+ #if !DECLITEND1423+ for (; ut>=acc+4; ut-=4, us-=4) { // big-endian add loop1424+ // bcd8 add1425+ carry+=UBTOUI(us); // rhs + carry1426+ if (carry==0) continue; // no-op1427+ carry+=UBTOUI(ut); // lhs1428+ // Big-endian BCD adjust (uses internal carry)1429+ carry+=0x76f6f6f6; // note top nibble not all bits1430+ // apply BCD adjust and save1431+ UBFROMUI(ut, (carry & 0x0f0f0f0f) - ((carry & 0x60606060)>>4));1432+ carry>>=31; // true carry was at far left1433+ } // add loop1434+ #else1435+ for (; ut>=acc+4; ut-=4, us-=4) { // little-endian add loop1436+ // bcd8 add1437+ carry+=UBTOUI(us); // rhs + carry1438+ if (carry==0) continue; // no-op [common if unaligned]1439+ carry+=UBTOUI(ut); // lhs1440+ // Little-endian BCD adjust; inter-digit carry must be manual1441+ // because the lsb from the array will be in the most-significant1442+ // byte of carry1443+ carry+=0x76767676; // note no inter-byte carries1444+ carry+=(carry & 0x80000000)>>15;1445+ carry+=(carry & 0x00800000)>>15;1446+ carry+=(carry & 0x00008000)>>15;1447+ carry-=(carry & 0x60606060)>>4; // BCD adjust back1448+ UBFROMUI(ut, carry & 0x0f0f0f0f); // clear debris and save1449+ // here, final carry-out bit is at 0x00000080; move it ready1450+ // for next word-add (i.e., to 0x01000000)1451+ carry=(carry & 0x00000080)<<17;1452+ } // add loop1453+ #endif1454+1455+ #if DECTRACE1456+ {bcdnum tum;1457+ printf("Add done, carry=%08lx, diffsign=%ld\n", (LI)carry, (LI)diffsign);1458+ tum.msd=umsd; // acc+4;1459+ tum.lsd=ulsd;1460+ tum.exponent=0;1461+ tum.sign=0;1462+ decShowNum(&tum, "dfadd");}1463+ #endif1464+ } // overlap possible1465+1466+ // ordering here is a little strange in order to have slowest path1467+ // first in GCC asm listing1468+ if (diffsign) { // subtraction1469+ if (!carry) { // no carry out means RHS<LHS1470+ // borrowed -- take ten's complement1471+ // sign is lhs sign1472+ num.sign=DFWORD(dfl, 0) & DECFLOAT_Sign;1473+1474+ // invert the coefficient first by fours, then add one; space1475+ // at the end of the buffer ensures the by-fours is always1476+ // safe, but lsd+1 must be cleared to prevent a borrow1477+ // if big-endian1478+ #if !DECLITEND1479+ *(ulsd+1)=0;1480+ #endif1481+ // there are always at least four coefficient words1482+ UBFROMUI(umsd, 0x09090909-UBTOUI(umsd));1483+ UBFROMUI(umsd+4, 0x09090909-UBTOUI(umsd+4));1484+ UBFROMUI(umsd+8, 0x09090909-UBTOUI(umsd+8));1485+ UBFROMUI(umsd+12, 0x09090909-UBTOUI(umsd+12));1486+ #if DOUBLE1487+ #define BNEXT 161488+ #elif QUAD1489+ UBFROMUI(umsd+16, 0x09090909-UBTOUI(umsd+16));1490+ UBFROMUI(umsd+20, 0x09090909-UBTOUI(umsd+20));1491+ UBFROMUI(umsd+24, 0x09090909-UBTOUI(umsd+24));1492+ UBFROMUI(umsd+28, 0x09090909-UBTOUI(umsd+28));1493+ UBFROMUI(umsd+32, 0x09090909-UBTOUI(umsd+32));1494+ #define BNEXT 361495+ #endif1496+ if (ulsd>=umsd+BNEXT) { // unaligned1497+ // eight will handle most unaligments for Double; 16 for Quad1498+ UBFROMUI(umsd+BNEXT, 0x09090909-UBTOUI(umsd+BNEXT));1499+ UBFROMUI(umsd+BNEXT+4, 0x09090909-UBTOUI(umsd+BNEXT+4));1500+ #if DOUBLE1501+ #define BNEXTY (BNEXT+8)1502+ #elif QUAD1503+ UBFROMUI(umsd+BNEXT+8, 0x09090909-UBTOUI(umsd+BNEXT+8));1504+ UBFROMUI(umsd+BNEXT+12, 0x09090909-UBTOUI(umsd+BNEXT+12));1505+ #define BNEXTY (BNEXT+16)1506+ #endif1507+ if (ulsd>=umsd+BNEXTY) { // very unaligned1508+ ut=umsd+BNEXTY; // -> continue1509+ for (;;ut+=4) {1510+ UBFROMUI(ut, 0x09090909-UBTOUI(ut)); // invert four digits1511+ if (ut>=ulsd-3) break; // all done1512+ }1513+ }1514+ }1515+ // complete the ten's complement by adding 11516+ for (ub=ulsd; *ub==9; ub--) *ub=0;1517+ *ub+=1;1518+ } // borrowed1519+1520+ else { // carry out means RHS>=LHS1521+ num.sign=DFWORD(dfr, 0) & DECFLOAT_Sign;1522+ // all done except for the special IEEE 754 exact-zero-result1523+ // rule (see above); while testing for zero, strip leading1524+ // zeros (which will save decFinalize doing it) (this is in1525+ // diffsign path, so carry impossible and true umsd is1526+ // acc+COFF)1527+1528+ // Check the initial coefficient area using the fast macro;1529+ // this will often be all that needs to be done (as on the1530+ // worst-case path when the subtraction was aligned and1531+ // full-length)1532+ if (ISCOEFFZERO(acc+COFF)) {1533+ umsd=acc+COFF+DECPMAX-1; // so far, so zero1534+ if (ulsd>umsd) { // more to check1535+ umsd++; // to align after checked area1536+ for (; UBTOUI(umsd)==0 && umsd+3<ulsd;) umsd+=4;1537+ for (; *umsd==0 && umsd<ulsd;) umsd++;1538+ }1539+ if (*umsd==0) { // must be true zero (and diffsign)1540+ num.sign=0; // assume +1541+ if (set->round==DEC_ROUND_FLOOR) num.sign=DECFLOAT_Sign;1542+ }1543+ }1544+ // [else was not zero, might still have leading zeros]1545+ } // subtraction gave positive result1546+ } // diffsign1547+1548+ else { // same-sign addition1549+ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;1550+ #if DOUBLE1551+ if (carry) { // only possible with decDouble1552+ *(acc+3)=1; // [Quad has leading 00]1553+ umsd=acc+3;1554+ }1555+ #endif1556+ } // same sign1557+1558+ num.msd=umsd; // set MSD ..1559+ num.lsd=ulsd; // .. and LSD1560+ num.exponent=bexpr-DECBIAS; // set exponent to smaller, unbiassed1561+1562+ #if DECTRACE1563+ decFloatShow(dfl, "dfl");1564+ decFloatShow(dfr, "dfr");1565+ decShowNum(&num, "postadd");1566+ #endif1567+ return decFinalize(result, &num, set); // round, check, and lay out1568+ } // decFloatAdd1569+1570+/* ------------------------------------------------------------------ */1571+/* decFloatAnd -- logical digitwise AND of two decFloats */1572+/* */1573+/* result gets the result of ANDing dfl and dfr */1574+/* dfl is the first decFloat (lhs) */1575+/* dfr is the second decFloat (rhs) */1576+/* set is the context */1577+/* returns result, which will be canonical with sign=0 */1578+/* */1579+/* The operands must be positive, finite with exponent q=0, and */1580+/* comprise just zeros and ones; if not, Invalid operation results. */1581+/* ------------------------------------------------------------------ */1582+decFloat * decFloatAnd(decFloat *result,1583+ const decFloat *dfl, const decFloat *dfr,1584+ decContext *set) {1585+ if (!DFISUINT01(dfl) || !DFISUINT01(dfr)1586+ || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);1587+ // the operands are positive finite integers (q=0) with just 0s and 1s1588+ #if DOUBLE1589+ DFWORD(result, 0)=ZEROWORD1590+ |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04009124);1591+ DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x49124491;1592+ #elif QUAD1593+ DFWORD(result, 0)=ZEROWORD1594+ |((DFWORD(dfl, 0) & DFWORD(dfr, 0))&0x04000912);1595+ DFWORD(result, 1)=(DFWORD(dfl, 1) & DFWORD(dfr, 1))&0x44912449;1596+ DFWORD(result, 2)=(DFWORD(dfl, 2) & DFWORD(dfr, 2))&0x12449124;1597+ DFWORD(result, 3)=(DFWORD(dfl, 3) & DFWORD(dfr, 3))&0x49124491;1598+ #endif1599+ return result;1600+ } // decFloatAnd1601+1602+/* ------------------------------------------------------------------ */1603+/* decFloatCanonical -- copy a decFloat, making canonical */1604+/* */1605+/* result gets the canonicalized df */1606+/* df is the decFloat to copy and make canonical */1607+/* returns result */1608+/* */1609+/* This works on specials, too; no error or exception is possible. */1610+/* ------------------------------------------------------------------ */1611+decFloat * decFloatCanonical(decFloat *result, const decFloat *df) {1612+ return decCanonical(result, df);1613+ } // decFloatCanonical1614+1615+/* ------------------------------------------------------------------ */1616+/* decFloatClass -- return the class of a decFloat */1617+/* */1618+/* df is the decFloat to test */1619+/* returns the decClass that df falls into */1620+/* ------------------------------------------------------------------ */1621+enum decClass decFloatClass(const decFloat *df) {1622+ Int exp; // exponent1623+ if (DFISSPECIAL(df)) {1624+ if (DFISQNAN(df)) return DEC_CLASS_QNAN;1625+ if (DFISSNAN(df)) return DEC_CLASS_SNAN;1626+ // must be an infinity1627+ if (DFISSIGNED(df)) return DEC_CLASS_NEG_INF;1628+ return DEC_CLASS_POS_INF;1629+ }1630+ if (DFISZERO(df)) { // quite common1631+ if (DFISSIGNED(df)) return DEC_CLASS_NEG_ZERO;1632+ return DEC_CLASS_POS_ZERO;1633+ }1634+ // is finite and non-zero; similar code to decFloatIsNormal, here1635+ // [this could be speeded up slightly by in-lining decFloatDigits]1636+ exp=GETEXPUN(df) // get unbiased exponent ..1637+ +decFloatDigits(df)-1; // .. and make adjusted exponent1638+ if (exp>=DECEMIN) { // is normal1639+ if (DFISSIGNED(df)) return DEC_CLASS_NEG_NORMAL;1640+ return DEC_CLASS_POS_NORMAL;1641+ }1642+ // is subnormal1643+ if (DFISSIGNED(df)) return DEC_CLASS_NEG_SUBNORMAL;1644+ return DEC_CLASS_POS_SUBNORMAL;1645+ } // decFloatClass1646+1647+/* ------------------------------------------------------------------ */1648+/* decFloatClassString -- return the class of a decFloat as a string */1649+/* */1650+/* df is the decFloat to test */1651+/* returns a constant string describing the class df falls into */1652+/* ------------------------------------------------------------------ */1653+const char *decFloatClassString(const decFloat *df) {1654+ enum decClass eclass=decFloatClass(df);1655+ if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;1656+ if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;1657+ if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;1658+ if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;1659+ if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;1660+ if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;1661+ if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;1662+ if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;1663+ if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;1664+ if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;1665+ return DEC_ClassString_UN; // Unknown1666+ } // decFloatClassString1667+1668+/* ------------------------------------------------------------------ */1669+/* decFloatCompare -- compare two decFloats; quiet NaNs allowed */1670+/* */1671+/* result gets the result of comparing dfl and dfr */1672+/* dfl is the first decFloat (lhs) */1673+/* dfr is the second decFloat (rhs) */1674+/* set is the context */1675+/* returns result, which may be -1, 0, 1, or NaN (Unordered) */1676+/* ------------------------------------------------------------------ */1677+decFloat * decFloatCompare(decFloat *result,1678+ const decFloat *dfl, const decFloat *dfr,1679+ decContext *set) {1680+ Int comp; // work1681+ // NaNs are handled as usual1682+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);1683+ // numeric comparison needed1684+ comp=decNumCompare(dfl, dfr, 0);1685+ decFloatZero(result);1686+ if (comp==0) return result;1687+ DFBYTE(result, DECBYTES-1)=0x01; // LSD=11688+ if (comp<0) DFBYTE(result, 0)|=0x80; // set sign bit1689+ return result;1690+ } // decFloatCompare1691+1692+/* ------------------------------------------------------------------ */1693+/* decFloatCompareSignal -- compare two decFloats; all NaNs signal */1694+/* */1695+/* result gets the result of comparing dfl and dfr */1696+/* dfl is the first decFloat (lhs) */1697+/* dfr is the second decFloat (rhs) */1698+/* set is the context */1699+/* returns result, which may be -1, 0, 1, or NaN (Unordered) */1700+/* ------------------------------------------------------------------ */1701+decFloat * decFloatCompareSignal(decFloat *result,1702+ const decFloat *dfl, const decFloat *dfr,1703+ decContext *set) {1704+ Int comp; // work1705+ // NaNs are handled as usual, except that all NaNs signal1706+ if (DFISNAN(dfl) || DFISNAN(dfr)) {1707+ set->status|=DEC_Invalid_operation;1708+ return decNaNs(result, dfl, dfr, set);1709+ }1710+ // numeric comparison needed1711+ comp=decNumCompare(dfl, dfr, 0);1712+ decFloatZero(result);1713+ if (comp==0) return result;1714+ DFBYTE(result, DECBYTES-1)=0x01; // LSD=11715+ if (comp<0) DFBYTE(result, 0)|=0x80; // set sign bit1716+ return result;1717+ } // decFloatCompareSignal1718+1719+/* ------------------------------------------------------------------ */1720+/* decFloatCompareTotal -- compare two decFloats with total ordering */1721+/* */1722+/* result gets the result of comparing dfl and dfr */1723+/* dfl is the first decFloat (lhs) */1724+/* dfr is the second decFloat (rhs) */1725+/* returns result, which may be -1, 0, or 1 */1726+/* ------------------------------------------------------------------ */1727+decFloat * decFloatCompareTotal(decFloat *result,1728+ const decFloat *dfl, const decFloat *dfr) {1729+ Int comp; // work1730+ uInt uiwork; // for macros1731+ #if QUAD1732+ uShort uswork; // ..1733+ #endif1734+ if (DFISNAN(dfl) || DFISNAN(dfr)) {1735+ Int nanl, nanr; // work1736+ // morph NaNs to +/- 1 or 2, leave numbers as 01737+ nanl=DFISSNAN(dfl)+DFISQNAN(dfl)*2; // quiet > signalling1738+ if (DFISSIGNED(dfl)) nanl=-nanl;1739+ nanr=DFISSNAN(dfr)+DFISQNAN(dfr)*2;1740+ if (DFISSIGNED(dfr)) nanr=-nanr;1741+ if (nanl>nanr) comp=+1;1742+ else if (nanl<nanr) comp=-1;1743+ else { // NaNs are the same type and sign .. must compare payload1744+ // buffers need +2 for QUAD1745+ uByte bufl[DECPMAX+4]; // for LHS coefficient + foot1746+ uByte bufr[DECPMAX+4]; // for RHS coefficient + foot1747+ uByte *ub, *uc; // work1748+ Int sigl; // signum of LHS1749+ sigl=(DFISSIGNED(dfl) ? -1 : +1);1750+1751+ // decode the coefficients1752+ // (shift both right two if Quad to make a multiple of four)1753+ #if QUAD1754+ UBFROMUS(bufl, 0);1755+ UBFROMUS(bufr, 0);1756+ #endif1757+ GETCOEFF(dfl, bufl+QUAD*2); // decode from decFloat1758+ GETCOEFF(dfr, bufr+QUAD*2); // ..1759+ // all multiples of four, here1760+ comp=0; // assume equal1761+ for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {1762+ uInt ui=UBTOUI(ub);1763+ if (ui==UBTOUI(uc)) continue; // so far so same1764+ // about to find a winner; go by bytes in case little-endian1765+ for (;; ub++, uc++) {1766+ if (*ub==*uc) continue;1767+ if (*ub>*uc) comp=sigl; // difference found1768+ else comp=-sigl; // ..1769+ break;1770+ }1771+ }1772+ } // same NaN type and sign1773+ }1774+ else {1775+ // numeric comparison needed1776+ comp=decNumCompare(dfl, dfr, 1); // total ordering1777+ }1778+ decFloatZero(result);1779+ if (comp==0) return result;1780+ DFBYTE(result, DECBYTES-1)=0x01; // LSD=11781+ if (comp<0) DFBYTE(result, 0)|=0x80; // set sign bit1782+ return result;1783+ } // decFloatCompareTotal1784+1785+/* ------------------------------------------------------------------ */1786+/* decFloatCompareTotalMag -- compare magnitudes with total ordering */1787+/* */1788+/* result gets the result of comparing abs(dfl) and abs(dfr) */1789+/* dfl is the first decFloat (lhs) */1790+/* dfr is the second decFloat (rhs) */1791+/* returns result, which may be -1, 0, or 1 */1792+/* ------------------------------------------------------------------ */1793+decFloat * decFloatCompareTotalMag(decFloat *result,1794+ const decFloat *dfl, const decFloat *dfr) {1795+ decFloat a, b; // for copy if needed1796+ // copy and redirect signed operand(s)1797+ if (DFISSIGNED(dfl)) {1798+ decFloatCopyAbs(&a, dfl);1799+ dfl=&a;1800+ }1801+ if (DFISSIGNED(dfr)) {1802+ decFloatCopyAbs(&b, dfr);1803+ dfr=&b;1804+ }1805+ return decFloatCompareTotal(result, dfl, dfr);1806+ } // decFloatCompareTotalMag1807+1808+/* ------------------------------------------------------------------ */1809+/* decFloatCopy -- copy a decFloat as-is */1810+/* */1811+/* result gets the copy of dfl */1812+/* dfl is the decFloat to copy */1813+/* returns result */1814+/* */1815+/* This is a bitwise operation; no errors or exceptions are possible. */1816+/* ------------------------------------------------------------------ */1817+decFloat * decFloatCopy(decFloat *result, const decFloat *dfl) {1818+ if (dfl!=result) *result=*dfl; // copy needed1819+ return result;1820+ } // decFloatCopy1821+1822+/* ------------------------------------------------------------------ */1823+/* decFloatCopyAbs -- copy a decFloat as-is and set sign bit to 0 */1824+/* */1825+/* result gets the copy of dfl with sign bit 0 */1826+/* dfl is the decFloat to copy */1827+/* returns result */1828+/* */1829+/* This is a bitwise operation; no errors or exceptions are possible. */1830+/* ------------------------------------------------------------------ */1831+decFloat * decFloatCopyAbs(decFloat *result, const decFloat *dfl) {1832+ if (dfl!=result) *result=*dfl; // copy needed1833+ DFBYTE(result, 0)&=~0x80; // zero sign bit1834+ return result;1835+ } // decFloatCopyAbs1836+1837+/* ------------------------------------------------------------------ */1838+/* decFloatCopyNegate -- copy a decFloat as-is with inverted sign bit */1839+/* */1840+/* result gets the copy of dfl with sign bit inverted */1841+/* dfl is the decFloat to copy */1842+/* returns result */1843+/* */1844+/* This is a bitwise operation; no errors or exceptions are possible. */1845+/* ------------------------------------------------------------------ */1846+decFloat * decFloatCopyNegate(decFloat *result, const decFloat *dfl) {1847+ if (dfl!=result) *result=*dfl; // copy needed1848+ DFBYTE(result, 0)^=0x80; // invert sign bit1849+ return result;1850+ } // decFloatCopyNegate1851+1852+/* ------------------------------------------------------------------ */1853+/* decFloatCopySign -- copy a decFloat with the sign of another */1854+/* */1855+/* result gets the result of copying dfl with the sign of dfr */1856+/* dfl is the first decFloat (lhs) */1857+/* dfr is the second decFloat (rhs) */1858+/* returns result */1859+/* */1860+/* This is a bitwise operation; no errors or exceptions are possible. */1861+/* ------------------------------------------------------------------ */1862+decFloat * decFloatCopySign(decFloat *result,1863+ const decFloat *dfl, const decFloat *dfr) {1864+ uByte sign=(uByte)(DFBYTE(dfr, 0)&0x80); // save sign bit1865+ if (dfl!=result) *result=*dfl; // copy needed1866+ DFBYTE(result, 0)&=~0x80; // clear sign ..1867+ DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); // .. and set saved1868+ return result;1869+ } // decFloatCopySign1870+1871+/* ------------------------------------------------------------------ */1872+/* decFloatDigits -- return the number of digits in a decFloat */1873+/* */1874+/* df is the decFloat to investigate */1875+/* returns the number of significant digits in the decFloat; a */1876+/* zero coefficient returns 1 as does an infinity (a NaN returns */1877+/* the number of digits in the payload) */1878+/* ------------------------------------------------------------------ */1879+// private macro to extract a declet according to provided formula1880+// (form), and if it is non-zero then return the calculated digits1881+// depending on the declet number (n), where n=0 for the most1882+// significant declet; uses uInt dpd for work1883+#define dpdlenchk(n, form) dpd=(form)&0x3ff; \1884+ if (dpd) return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3])1885+// next one is used when it is known that the declet must be1886+// non-zero, or is the final zero declet1887+#define dpdlendun(n, form) dpd=(form)&0x3ff; \1888+ if (dpd==0) return 1; \1889+ return (DECPMAX-1-3*(n))-(3-DPD2BCD8[dpd*4+3])1890+1891+uInt decFloatDigits(const decFloat *df) {1892+ uInt dpd; // work1893+ uInt sourhi=DFWORD(df, 0); // top word from source decFloat1894+ #if QUAD1895+ uInt sourmh, sourml;1896+ #endif1897+ uInt sourlo;1898+1899+ if (DFISINF(df)) return 1;1900+ // A NaN effectively has an MSD of 0; otherwise if non-zero MSD1901+ // then the coefficient is full-length1902+ if (!DFISNAN(df) && DECCOMBMSD[sourhi>>26]) return DECPMAX;1903+1904+ #if DOUBLE1905+ if (sourhi&0x0003ffff) { // ends in first1906+ dpdlenchk(0, sourhi>>8);1907+ sourlo=DFWORD(df, 1);1908+ dpdlendun(1, (sourhi<<2) | (sourlo>>30));1909+ } // [cannot drop through]1910+ sourlo=DFWORD(df, 1); // sourhi not involved now1911+ if (sourlo&0xfff00000) { // in one of first two1912+ dpdlenchk(1, sourlo>>30); // very rare1913+ dpdlendun(2, sourlo>>20);1914+ } // [cannot drop through]1915+ dpdlenchk(3, sourlo>>10);1916+ dpdlendun(4, sourlo);1917+ // [cannot drop through]1918+1919+ #elif QUAD1920+ if (sourhi&0x00003fff) { // ends in first1921+ dpdlenchk(0, sourhi>>4);1922+ sourmh=DFWORD(df, 1);1923+ dpdlendun(1, ((sourhi)<<6) | (sourmh>>26));1924+ } // [cannot drop through]1925+ sourmh=DFWORD(df, 1);1926+ if (sourmh) {1927+ dpdlenchk(1, sourmh>>26);1928+ dpdlenchk(2, sourmh>>16);1929+ dpdlenchk(3, sourmh>>6);1930+ sourml=DFWORD(df, 2);1931+ dpdlendun(4, ((sourmh)<<4) | (sourml>>28));1932+ } // [cannot drop through]1933+ sourml=DFWORD(df, 2);1934+ if (sourml) {1935+ dpdlenchk(4, sourml>>28);1936+ dpdlenchk(5, sourml>>18);1937+ dpdlenchk(6, sourml>>8);1938+ sourlo=DFWORD(df, 3);1939+ dpdlendun(7, ((sourml)<<2) | (sourlo>>30));1940+ } // [cannot drop through]1941+ sourlo=DFWORD(df, 3);1942+ if (sourlo&0xfff00000) { // in one of first two1943+ dpdlenchk(7, sourlo>>30); // very rare1944+ dpdlendun(8, sourlo>>20);1945+ } // [cannot drop through]1946+ dpdlenchk(9, sourlo>>10);1947+ dpdlendun(10, sourlo);1948+ // [cannot drop through]1949+ #endif1950+ } // decFloatDigits1951+1952+/* ------------------------------------------------------------------ */1953+/* decFloatDivide -- divide a decFloat by another */1954+/* */1955+/* result gets the result of dividing dfl by dfr: */1956+/* dfl is the first decFloat (lhs) */1957+/* dfr is the second decFloat (rhs) */1958+/* set is the context */1959+/* returns result */1960+/* */1961+/* ------------------------------------------------------------------ */1962+// This is just a wrapper.1963+decFloat * decFloatDivide(decFloat *result,1964+ const decFloat *dfl, const decFloat *dfr,1965+ decContext *set) {1966+ return decDivide(result, dfl, dfr, set, DIVIDE);1967+ } // decFloatDivide1968+1969+/* ------------------------------------------------------------------ */1970+/* decFloatDivideInteger -- integer divide a decFloat by another */1971+/* */1972+/* result gets the result of dividing dfl by dfr: */1973+/* dfl is the first decFloat (lhs) */1974+/* dfr is the second decFloat (rhs) */1975+/* set is the context */1976+/* returns result */1977+/* */1978+/* ------------------------------------------------------------------ */1979+decFloat * decFloatDivideInteger(decFloat *result,1980+ const decFloat *dfl, const decFloat *dfr,1981+ decContext *set) {1982+ return decDivide(result, dfl, dfr, set, DIVIDEINT);1983+ } // decFloatDivideInteger1984+1985+/* ------------------------------------------------------------------ */1986+/* decFloatFMA -- multiply and add three decFloats, fused */1987+/* */1988+/* result gets the result of (dfl*dfr)+dff with a single rounding */1989+/* dfl is the first decFloat (lhs) */1990+/* dfr is the second decFloat (rhs) */1991+/* dff is the final decFloat (fhs) */1992+/* set is the context */1993+/* returns result */1994+/* */1995+/* ------------------------------------------------------------------ */1996+decFloat * decFloatFMA(decFloat *result, const decFloat *dfl,1997+ const decFloat *dfr, const decFloat *dff,1998+ decContext *set) {1999+2000+ // The accumulator has the bytes needed for FiniteMultiply, plus2001+ // one byte to the left in case of carry, plus DECPMAX+2 to the2002+ // right for the final addition (up to full fhs + round & sticky)2003+ #define FMALEN (ROUNDUP4(1+ (DECPMAX9*18+1) +DECPMAX+2))2004+ uByte acc[FMALEN]; // for multiplied coefficient in BCD2005+ // .. and for final result2006+ bcdnum mul; // for multiplication result2007+ bcdnum fin; // for final operand, expanded2008+ uByte coe[ROUNDUP4(DECPMAX)]; // dff coefficient in BCD2009+ bcdnum *hi, *lo; // bcdnum with higher/lower exponent2010+ uInt diffsign; // non-zero if signs differ2011+ uInt hipad; // pad digit for hi if needed2012+ Int padding; // excess exponent2013+ uInt carry; // +1 for ten's complement and during add2014+ uByte *ub, *uh, *ul; // work2015+ uInt uiwork; // for macros2016+2017+ // handle all the special values [any special operand leads to a2018+ // special result]2019+ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr) || DFISSPECIAL(dff)) {2020+ decFloat proxy; // multiplication result proxy2021+ // NaNs are handled as usual, giving priority to sNaNs2022+ if (DFISSNAN(dfl) || DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);2023+ if (DFISSNAN(dff)) return decNaNs(result, dff, NULL, set);2024+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);2025+ if (DFISNAN(dff)) return decNaNs(result, dff, NULL, set);2026+ // One or more of the three is infinite2027+ // infinity times zero is bad2028+ decFloatZero(&proxy);2029+ if (DFISINF(dfl)) {2030+ if (DFISZERO(dfr)) return decInvalid(result, set);2031+ decInfinity(&proxy, &proxy);2032+ }2033+ else if (DFISINF(dfr)) {2034+ if (DFISZERO(dfl)) return decInvalid(result, set);2035+ decInfinity(&proxy, &proxy);2036+ }2037+ // compute sign of multiplication and place in proxy2038+ DFWORD(&proxy, 0)|=(DFWORD(dfl, 0)^DFWORD(dfr, 0))&DECFLOAT_Sign;2039+ if (!DFISINF(dff)) return decFloatCopy(result, &proxy);2040+ // dff is Infinite2041+ if (!DFISINF(&proxy)) return decInfinity(result, dff);2042+ // both sides of addition are infinite; different sign is bad2043+ if ((DFWORD(dff, 0)&DECFLOAT_Sign)!=(DFWORD(&proxy, 0)&DECFLOAT_Sign))2044+ return decInvalid(result, set);2045+ return decFloatCopy(result, &proxy);2046+ }2047+2048+ /* Here when all operands are finite */2049+2050+ // First multiply dfl*dfr2051+ decFiniteMultiply(&mul, acc+1, dfl, dfr);2052+ // The multiply is complete, exact and unbounded, and described in2053+ // mul with the coefficient held in acc[1...]2054+2055+ // now add in dff; the algorithm is essentially the same as2056+ // decFloatAdd, but the code is different because the code there2057+ // is highly optimized for adding two numbers of the same size2058+ fin.exponent=GETEXPUN(dff); // get dff exponent and sign2059+ fin.sign=DFWORD(dff, 0)&DECFLOAT_Sign;2060+ diffsign=mul.sign^fin.sign; // note if signs differ2061+ fin.msd=coe;2062+ fin.lsd=coe+DECPMAX-1;2063+ GETCOEFF(dff, coe); // extract the coefficient2064+2065+ // now set hi and lo so that hi points to whichever of mul and fin2066+ // has the higher exponent and lo points to the other [don't care,2067+ // if the same]. One coefficient will be in acc, the other in coe.2068+ if (mul.exponent>=fin.exponent) {2069+ hi=&mul;2070+ lo=&fin;2071+ }2072+ else {2073+ hi=&fin;2074+ lo=&mul;2075+ }2076+2077+ // remove leading zeros on both operands; this will save time later2078+ // and make testing for zero trivial (tests are safe because acc2079+ // and coe are rounded up to uInts)2080+ for (; UBTOUI(hi->msd)==0 && hi->msd+3<hi->lsd;) hi->msd+=4;2081+ for (; *hi->msd==0 && hi->msd<hi->lsd;) hi->msd++;2082+ for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;2083+ for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;2084+2085+ // if hi is zero then result will be lo (which has the smaller2086+ // exponent), which also may need to be tested for zero for the2087+ // weird IEEE 754 sign rules2088+ if (*hi->msd==0) { // hi is zero2089+ // "When the sum of two operands with opposite signs is2090+ // exactly zero, the sign of that sum shall be '+' in all2091+ // rounding modes except round toward -Infinity, in which2092+ // mode that sign shall be '-'."2093+ if (diffsign) {2094+ if (*lo->msd==0) { // lo is zero2095+ lo->sign=0;2096+ if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;2097+ } // diffsign && lo=02098+ } // diffsign2099+ return decFinalize(result, lo, set); // may need clamping2100+ } // numfl is zero2101+ // [here, both are minimal length and hi is non-zero]2102+ // (if lo is zero then padding with zeros may be needed, below)2103+2104+ // if signs differ, take the ten's complement of hi (zeros to the2105+ // right do not matter because the complement of zero is zero); the2106+ // +1 is done later, as part of the addition, inserted at the2107+ // correct digit2108+ hipad=0;2109+ carry=0;2110+ if (diffsign) {2111+ hipad=9;2112+ carry=1;2113+ // exactly the correct number of digits must be inverted2114+ for (uh=hi->msd; uh<hi->lsd-3; uh+=4) UBFROMUI(uh, 0x09090909-UBTOUI(uh));2115+ for (; uh<=hi->lsd; uh++) *uh=(uByte)(0x09-*uh);2116+ }2117+2118+ // ready to add; note that hi has no leading zeros so gap2119+ // calculation does not have to be as pessimistic as in decFloatAdd2120+ // (this is much more like the arbitrary-precision algorithm in2121+ // Rexx and decNumber)2122+2123+ // padding is the number of zeros that would need to be added to hi2124+ // for its lsd to be aligned with the lsd of lo2125+ padding=hi->exponent-lo->exponent;2126+ // printf("FMA pad %ld\n", (LI)padding);2127+2128+ // the result of the addition will be built into the accumulator,2129+ // starting from the far right; this could be either hi or lo, and2130+ // will be aligned2131+ ub=acc+FMALEN-1; // where lsd of result will go2132+ ul=lo->lsd; // lsd of rhs2133+2134+ if (padding!=0) { // unaligned2135+ // if the msd of lo is more than DECPMAX+2 digits to the right of2136+ // the original msd of hi then it can be reduced to a single2137+ // digit at the right place, as it stays clear of hi digits2138+ // [it must be DECPMAX+2 because during a subtraction the msd2139+ // could become 0 after a borrow from 1.000 to 0.9999...]2140+2141+ Int hilen=(Int)(hi->lsd-hi->msd+1); // length of hi2142+ Int lolen=(Int)(lo->lsd-lo->msd+1); // and of lo2143+2144+ if (hilen+padding-lolen > DECPMAX+2) { // can reduce lo to single2145+ // make sure it is virtually at least DECPMAX from hi->msd, at2146+ // least to right of hi->lsd (in case of destructive subtract),2147+ // and separated by at least two digits from either of those2148+ // (the tricky DOUBLE case is when hi is a 1 that will become a2149+ // 0.9999... by subtraction:2150+ // hi: 1 E+162151+ // lo: .................1000000000000000 E-162152+ // which for the addition pads to:2153+ // hi: 1000000000000000000 E-162154+ // lo: .................1000000000000000 E-162155+ Int newexp=MINI(hi->exponent, hi->exponent+hilen-DECPMAX)-3;2156+2157+ // printf("FMA reduce: %ld\n", (LI)reduce);2158+ lo->lsd=lo->msd; // to single digit [maybe 0]2159+ lo->exponent=newexp; // new lowest exponent2160+ padding=hi->exponent-lo->exponent; // recalculate2161+ ul=lo->lsd; // .. and repoint2162+ }2163+2164+ // padding is still > 0, but will fit in acc (less leading carry slot)2165+ #if DECCHECK2166+ if (padding<=0) printf("FMA low padding: %ld\n", (LI)padding);2167+ if (hilen+padding+1>FMALEN)2168+ printf("FMA excess hilen+padding: %ld+%ld \n", (LI)hilen, (LI)padding);2169+ // printf("FMA padding: %ld\n", (LI)padding);2170+ #endif2171+2172+ // padding digits can now be set in the result; one or more of2173+ // these will come from lo; others will be zeros in the gap2174+ for (; ul-3>=lo->msd && padding>3; padding-=4, ul-=4, ub-=4) {2175+ UBFROMUI(ub-3, UBTOUI(ul-3)); // [cannot overlap]2176+ }2177+ for (; ul>=lo->msd && padding>0; padding--, ul--, ub--) *ub=*ul;2178+ for (;padding>0; padding--, ub--) *ub=0; // mind the gap2179+ }2180+2181+ // addition now complete to the right of the rightmost digit of hi2182+ uh=hi->lsd;2183+2184+ // dow do the add from hi->lsd to the left2185+ // [bytewise, because either operand can run out at any time]2186+ // carry was set up depending on ten's complement above2187+ // first assume both operands have some digits2188+ for (;; ub--) {2189+ if (uh<hi->msd || ul<lo->msd) break;2190+ *ub=(uByte)(carry+(*uh--)+(*ul--));2191+ carry=0;2192+ if (*ub<10) continue;2193+ *ub-=10;2194+ carry=1;2195+ } // both loop2196+2197+ if (ul<lo->msd) { // to left of lo2198+ for (;; ub--) {2199+ if (uh<hi->msd) break;2200+ *ub=(uByte)(carry+(*uh--)); // [+0]2201+ carry=0;2202+ if (*ub<10) continue;2203+ *ub-=10;2204+ carry=1;2205+ } // hi loop2206+ }2207+ else { // to left of hi2208+ for (;; ub--) {2209+ if (ul<lo->msd) break;2210+ *ub=(uByte)(carry+hipad+(*ul--));2211+ carry=0;2212+ if (*ub<10) continue;2213+ *ub-=10;2214+ carry=1;2215+ } // lo loop2216+ }2217+2218+ // addition complete -- now handle carry, borrow, etc.2219+ // use lo to set up the num (its exponent is already correct, and2220+ // sign usually is)2221+ lo->msd=ub+1;2222+ lo->lsd=acc+FMALEN-1;2223+ // decShowNum(lo, "lo");2224+ if (!diffsign) { // same-sign addition2225+ if (carry) { // carry out2226+ *ub=1; // place the 1 ..2227+ lo->msd--; // .. and update2228+ }2229+ } // same sign2230+ else { // signs differed (subtraction)2231+ if (!carry) { // no carry out means hi<lo2232+ // borrowed -- take ten's complement of the right digits2233+ lo->sign=hi->sign; // sign is lhs sign2234+ for (ul=lo->msd; ul<lo->lsd-3; ul+=4) UBFROMUI(ul, 0x09090909-UBTOUI(ul));2235+ for (; ul<=lo->lsd; ul++) *ul=(uByte)(0x09-*ul); // [leaves ul at lsd+1]2236+ // complete the ten's complement by adding 1 [cannot overrun]2237+ for (ul--; *ul==9; ul--) *ul=0;2238+ *ul+=1;2239+ } // borrowed2240+ else { // carry out means hi>=lo2241+ // sign to use is lo->sign2242+ // all done except for the special IEEE 754 exact-zero-result2243+ // rule (see above); while testing for zero, strip leading2244+ // zeros (which will save decFinalize doing it)2245+ for (; UBTOUI(lo->msd)==0 && lo->msd+3<lo->lsd;) lo->msd+=4;2246+ for (; *lo->msd==0 && lo->msd<lo->lsd;) lo->msd++;2247+ if (*lo->msd==0) { // must be true zero (and diffsign)2248+ lo->sign=0; // assume +2249+ if (set->round==DEC_ROUND_FLOOR) lo->sign=DECFLOAT_Sign;2250+ }2251+ // [else was not zero, might still have leading zeros]2252+ } // subtraction gave positive result2253+ } // diffsign2254+2255+ #if DECCHECK2256+ // assert no left underrun2257+ if (lo->msd<acc) {2258+ printf("FMA underrun by %ld \n", (LI)(acc-lo->msd));2259+ }2260+ #endif2261+2262+ return decFinalize(result, lo, set); // round, check, and lay out2263+ } // decFloatFMA2264+2265+/* ------------------------------------------------------------------ */2266+/* decFloatFromInt -- initialise a decFloat from an Int */2267+/* */2268+/* result gets the converted Int */2269+/* n is the Int to convert */2270+/* returns result */2271+/* */2272+/* The result is Exact; no errors or exceptions are possible. */2273+/* ------------------------------------------------------------------ */2274+decFloat * decFloatFromInt32(decFloat *result, Int n) {2275+ uInt u=(uInt)n; // copy as bits2276+ uInt encode; // work2277+ DFWORD(result, 0)=ZEROWORD; // always2278+ #if QUAD2279+ DFWORD(result, 1)=0;2280+ DFWORD(result, 2)=0;2281+ #endif2282+ if (n<0) { // handle -n with care2283+ // [This can be done without the test, but is then slightly slower]2284+ u=(~u)+1;2285+ DFWORD(result, 0)|=DECFLOAT_Sign;2286+ }2287+ // Since the maximum value of u now is 2**31, only the low word of2288+ // result is affected2289+ encode=BIN2DPD[u%1000];2290+ u/=1000;2291+ encode|=BIN2DPD[u%1000]<<10;2292+ u/=1000;2293+ encode|=BIN2DPD[u%1000]<<20;2294+ u/=1000; // now 0, 1, or 22295+ encode|=u<<30;2296+ DFWORD(result, DECWORDS-1)=encode;2297+ return result;2298+ } // decFloatFromInt322299+2300+/* ------------------------------------------------------------------ */2301+/* decFloatFromUInt -- initialise a decFloat from a uInt */2302+/* */2303+/* result gets the converted uInt */2304+/* n is the uInt to convert */2305+/* returns result */2306+/* */2307+/* The result is Exact; no errors or exceptions are possible. */2308+/* ------------------------------------------------------------------ */2309+decFloat * decFloatFromUInt32(decFloat *result, uInt u) {2310+ uInt encode; // work2311+ DFWORD(result, 0)=ZEROWORD; // always2312+ #if QUAD2313+ DFWORD(result, 1)=0;2314+ DFWORD(result, 2)=0;2315+ #endif2316+ encode=BIN2DPD[u%1000];2317+ u/=1000;2318+ encode|=BIN2DPD[u%1000]<<10;2319+ u/=1000;2320+ encode|=BIN2DPD[u%1000]<<20;2321+ u/=1000; // now 0 -> 42322+ encode|=u<<30;2323+ DFWORD(result, DECWORDS-1)=encode;2324+ DFWORD(result, DECWORDS-2)|=u>>2; // rarely non-zero2325+ return result;2326+ } // decFloatFromUInt322327+2328+/* ------------------------------------------------------------------ */2329+/* decFloatInvert -- logical digitwise INVERT of a decFloat */2330+/* */2331+/* result gets the result of INVERTing df */2332+/* df is the decFloat to invert */2333+/* set is the context */2334+/* returns result, which will be canonical with sign=0 */2335+/* */2336+/* The operand must be positive, finite with exponent q=0, and */2337+/* comprise just zeros and ones; if not, Invalid operation results. */2338+/* ------------------------------------------------------------------ */2339+decFloat * decFloatInvert(decFloat *result, const decFloat *df,2340+ decContext *set) {2341+ uInt sourhi=DFWORD(df, 0); // top word of dfs2342+2343+ if (!DFISUINT01(df) || !DFISCC01(df)) return decInvalid(result, set);2344+ // the operand is a finite integer (q=0)2345+ #if DOUBLE2346+ DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04009124);2347+ DFWORD(result, 1)=(~DFWORD(df, 1)) &0x49124491;2348+ #elif QUAD2349+ DFWORD(result, 0)=ZEROWORD|((~sourhi)&0x04000912);2350+ DFWORD(result, 1)=(~DFWORD(df, 1)) &0x44912449;2351+ DFWORD(result, 2)=(~DFWORD(df, 2)) &0x12449124;2352+ DFWORD(result, 3)=(~DFWORD(df, 3)) &0x49124491;2353+ #endif2354+ return result;2355+ } // decFloatInvert2356+2357+/* ------------------------------------------------------------------ */2358+/* decFloatIs -- decFloat tests (IsSigned, etc.) */2359+/* */2360+/* df is the decFloat to test */2361+/* returns 0 or 1 in a uInt */2362+/* */2363+/* Many of these could be macros, but having them as real functions */2364+/* is a little cleaner (and they can be referred to here by the */2365+/* generic names) */2366+/* ------------------------------------------------------------------ */2367+uInt decFloatIsCanonical(const decFloat *df) {2368+ if (DFISSPECIAL(df)) {2369+ if (DFISINF(df)) {2370+ if (DFWORD(df, 0)&ECONMASK) return 0; // exponent continuation2371+ if (!DFISCCZERO(df)) return 0; // coefficient continuation2372+ return 1;2373+ }2374+ // is a NaN2375+ if (DFWORD(df, 0)&ECONNANMASK) return 0; // exponent continuation2376+ if (DFISCCZERO(df)) return 1; // coefficient continuation2377+ // drop through to check payload2378+ }2379+ { // declare block2380+ #if DOUBLE2381+ uInt sourhi=DFWORD(df, 0);2382+ uInt sourlo=DFWORD(df, 1);2383+ if (CANONDPDOFF(sourhi, 8)2384+ && CANONDPDTWO(sourhi, sourlo, 30)2385+ && CANONDPDOFF(sourlo, 20)2386+ && CANONDPDOFF(sourlo, 10)2387+ && CANONDPDOFF(sourlo, 0)) return 1;2388+ #elif QUAD2389+ uInt sourhi=DFWORD(df, 0);2390+ uInt sourmh=DFWORD(df, 1);2391+ uInt sourml=DFWORD(df, 2);2392+ uInt sourlo=DFWORD(df, 3);2393+ if (CANONDPDOFF(sourhi, 4)2394+ && CANONDPDTWO(sourhi, sourmh, 26)2395+ && CANONDPDOFF(sourmh, 16)2396+ && CANONDPDOFF(sourmh, 6)2397+ && CANONDPDTWO(sourmh, sourml, 28)2398+ && CANONDPDOFF(sourml, 18)2399+ && CANONDPDOFF(sourml, 8)2400+ && CANONDPDTWO(sourml, sourlo, 30)2401+ && CANONDPDOFF(sourlo, 20)2402+ && CANONDPDOFF(sourlo, 10)2403+ && CANONDPDOFF(sourlo, 0)) return 1;2404+ #endif2405+ } // block2406+ return 0; // a declet is non-canonical2407+ }2408+2409+uInt decFloatIsFinite(const decFloat *df) {2410+ return !DFISSPECIAL(df);2411+ }2412+uInt decFloatIsInfinite(const decFloat *df) {2413+ return DFISINF(df);2414+ }2415+uInt decFloatIsInteger(const decFloat *df) {2416+ return DFISINT(df);2417+ }2418+uInt decFloatIsLogical(const decFloat *df) {2419+ return DFISUINT01(df) & DFISCC01(df);2420+ }2421+uInt decFloatIsNaN(const decFloat *df) {2422+ return DFISNAN(df);2423+ }2424+uInt decFloatIsNegative(const decFloat *df) {2425+ return DFISSIGNED(df) && !DFISZERO(df) && !DFISNAN(df);2426+ }2427+uInt decFloatIsNormal(const decFloat *df) {2428+ Int exp; // exponent2429+ if (DFISSPECIAL(df)) return 0;2430+ if (DFISZERO(df)) return 0;2431+ // is finite and non-zero2432+ exp=GETEXPUN(df) // get unbiased exponent ..2433+ +decFloatDigits(df)-1; // .. and make adjusted exponent2434+ return (exp>=DECEMIN); // < DECEMIN is subnormal2435+ }2436+uInt decFloatIsPositive(const decFloat *df) {2437+ return !DFISSIGNED(df) && !DFISZERO(df) && !DFISNAN(df);2438+ }2439+uInt decFloatIsSignaling(const decFloat *df) {2440+ return DFISSNAN(df);2441+ }2442+uInt decFloatIsSignalling(const decFloat *df) {2443+ return DFISSNAN(df);2444+ }2445+uInt decFloatIsSigned(const decFloat *df) {2446+ return DFISSIGNED(df);2447+ }2448+uInt decFloatIsSubnormal(const decFloat *df) {2449+ if (DFISSPECIAL(df)) return 0;2450+ // is finite2451+ if (decFloatIsNormal(df)) return 0;2452+ // it is <Nmin, but could be zero2453+ if (DFISZERO(df)) return 0;2454+ return 1; // is subnormal2455+ }2456+uInt decFloatIsZero(const decFloat *df) {2457+ return DFISZERO(df);2458+ } // decFloatIs...2459+2460+/* ------------------------------------------------------------------ */2461+/* decFloatLogB -- return adjusted exponent, by 754 rules */2462+/* */2463+/* result gets the adjusted exponent as an integer, or a NaN etc. */2464+/* df is the decFloat to be examined */2465+/* set is the context */2466+/* returns result */2467+/* */2468+/* Notable cases: */2469+/* A<0 -> Use |A| */2470+/* A=0 -> -Infinity (Division by zero) */2471+/* A=Infinite -> +Infinity (Exact) */2472+/* A=1 exactly -> 0 (Exact) */2473+/* NaNs are propagated as usual */2474+/* ------------------------------------------------------------------ */2475+decFloat * decFloatLogB(decFloat *result, const decFloat *df,2476+ decContext *set) {2477+ Int ae; // adjusted exponent2478+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set);2479+ if (DFISINF(df)) {2480+ DFWORD(result, 0)=0; // need +ve2481+ return decInfinity(result, result); // canonical +Infinity2482+ }2483+ if (DFISZERO(df)) {2484+ set->status|=DEC_Division_by_zero; // as per 7542485+ DFWORD(result, 0)=DECFLOAT_Sign; // make negative2486+ return decInfinity(result, result); // canonical -Infinity2487+ }2488+ ae=GETEXPUN(df) // get unbiased exponent ..2489+ +decFloatDigits(df)-1; // .. and make adjusted exponent2490+ // ae has limited range (3 digits for DOUBLE and 4 for QUAD), so2491+ // it is worth using a special case of decFloatFromInt322492+ DFWORD(result, 0)=ZEROWORD; // always2493+ if (ae<0) {2494+ DFWORD(result, 0)|=DECFLOAT_Sign; // -0 so far2495+ ae=-ae;2496+ }2497+ #if DOUBLE2498+ DFWORD(result, 1)=BIN2DPD[ae]; // a single declet2499+ #elif QUAD2500+ DFWORD(result, 1)=0;2501+ DFWORD(result, 2)=0;2502+ DFWORD(result, 3)=(ae/1000)<<10; // is <10, so need no DPD encode2503+ DFWORD(result, 3)|=BIN2DPD[ae%1000];2504+ #endif2505+ return result;2506+ } // decFloatLogB2507+2508+/* ------------------------------------------------------------------ */2509+/* decFloatMax -- return maxnum of two operands */2510+/* */2511+/* result gets the chosen decFloat */2512+/* dfl is the first decFloat (lhs) */2513+/* dfr is the second decFloat (rhs) */2514+/* set is the context */2515+/* returns result */2516+/* */2517+/* If just one operand is a quiet NaN it is ignored. */2518+/* ------------------------------------------------------------------ */2519+decFloat * decFloatMax(decFloat *result,2520+ const decFloat *dfl, const decFloat *dfr,2521+ decContext *set) {2522+ Int comp;2523+ if (DFISNAN(dfl)) {2524+ // sNaN or both NaNs leads to normal NaN processing2525+ if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);2526+ return decCanonical(result, dfr); // RHS is numeric2527+ }2528+ if (DFISNAN(dfr)) {2529+ // sNaN leads to normal NaN processing (both NaN handled above)2530+ if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);2531+ return decCanonical(result, dfl); // LHS is numeric2532+ }2533+ // Both operands are numeric; numeric comparison needed -- use2534+ // total order for a well-defined choice (and +0 > -0)2535+ comp=decNumCompare(dfl, dfr, 1);2536+ if (comp>=0) return decCanonical(result, dfl);2537+ return decCanonical(result, dfr);2538+ } // decFloatMax2539+2540+/* ------------------------------------------------------------------ */2541+/* decFloatMaxMag -- return maxnummag of two operands */2542+/* */2543+/* result gets the chosen decFloat */2544+/* dfl is the first decFloat (lhs) */2545+/* dfr is the second decFloat (rhs) */2546+/* set is the context */2547+/* returns result */2548+/* */2549+/* Returns according to the magnitude comparisons if both numeric and */2550+/* unequal, otherwise returns maxnum */2551+/* ------------------------------------------------------------------ */2552+decFloat * decFloatMaxMag(decFloat *result,2553+ const decFloat *dfl, const decFloat *dfr,2554+ decContext *set) {2555+ Int comp;2556+ decFloat absl, absr;2557+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMax(result, dfl, dfr, set);2558+2559+ decFloatCopyAbs(&absl, dfl);2560+ decFloatCopyAbs(&absr, dfr);2561+ comp=decNumCompare(&absl, &absr, 0);2562+ if (comp>0) return decCanonical(result, dfl);2563+ if (comp<0) return decCanonical(result, dfr);2564+ return decFloatMax(result, dfl, dfr, set);2565+ } // decFloatMaxMag2566+2567+/* ------------------------------------------------------------------ */2568+/* decFloatMin -- return minnum of two operands */2569+/* */2570+/* result gets the chosen decFloat */2571+/* dfl is the first decFloat (lhs) */2572+/* dfr is the second decFloat (rhs) */2573+/* set is the context */2574+/* returns result */2575+/* */2576+/* If just one operand is a quiet NaN it is ignored. */2577+/* ------------------------------------------------------------------ */2578+decFloat * decFloatMin(decFloat *result,2579+ const decFloat *dfl, const decFloat *dfr,2580+ decContext *set) {2581+ Int comp;2582+ if (DFISNAN(dfl)) {2583+ // sNaN or both NaNs leads to normal NaN processing2584+ if (DFISNAN(dfr) || DFISSNAN(dfl)) return decNaNs(result, dfl, dfr, set);2585+ return decCanonical(result, dfr); // RHS is numeric2586+ }2587+ if (DFISNAN(dfr)) {2588+ // sNaN leads to normal NaN processing (both NaN handled above)2589+ if (DFISSNAN(dfr)) return decNaNs(result, dfl, dfr, set);2590+ return decCanonical(result, dfl); // LHS is numeric2591+ }2592+ // Both operands are numeric; numeric comparison needed -- use2593+ // total order for a well-defined choice (and +0 > -0)2594+ comp=decNumCompare(dfl, dfr, 1);2595+ if (comp<=0) return decCanonical(result, dfl);2596+ return decCanonical(result, dfr);2597+ } // decFloatMin2598+2599+/* ------------------------------------------------------------------ */2600+/* decFloatMinMag -- return minnummag of two operands */2601+/* */2602+/* result gets the chosen decFloat */2603+/* dfl is the first decFloat (lhs) */2604+/* dfr is the second decFloat (rhs) */2605+/* set is the context */2606+/* returns result */2607+/* */2608+/* Returns according to the magnitude comparisons if both numeric and */2609+/* unequal, otherwise returns minnum */2610+/* ------------------------------------------------------------------ */2611+decFloat * decFloatMinMag(decFloat *result,2612+ const decFloat *dfl, const decFloat *dfr,2613+ decContext *set) {2614+ Int comp;2615+ decFloat absl, absr;2616+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decFloatMin(result, dfl, dfr, set);2617+2618+ decFloatCopyAbs(&absl, dfl);2619+ decFloatCopyAbs(&absr, dfr);2620+ comp=decNumCompare(&absl, &absr, 0);2621+ if (comp<0) return decCanonical(result, dfl);2622+ if (comp>0) return decCanonical(result, dfr);2623+ return decFloatMin(result, dfl, dfr, set);2624+ } // decFloatMinMag2625+2626+/* ------------------------------------------------------------------ */2627+/* decFloatMinus -- negate value, heeding NaNs, etc. */2628+/* */2629+/* result gets the canonicalized 0-df */2630+/* df is the decFloat to minus */2631+/* set is the context */2632+/* returns result */2633+/* */2634+/* This has the same effect as 0-df where the exponent of the zero is */2635+/* the same as that of df (if df is finite). */2636+/* The effect is also the same as decFloatCopyNegate except that NaNs */2637+/* are handled normally (the sign of a NaN is not affected, and an */2638+/* sNaN will signal), the result is canonical, and zero gets sign 0. */2639+/* ------------------------------------------------------------------ */2640+decFloat * decFloatMinus(decFloat *result, const decFloat *df,2641+ decContext *set) {2642+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set);2643+ decCanonical(result, df); // copy and check2644+ if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; // turn off sign bit2645+ else DFBYTE(result, 0)^=0x80; // flip sign bit2646+ return result;2647+ } // decFloatMinus2648+2649+/* ------------------------------------------------------------------ */2650+/* decFloatMultiply -- multiply two decFloats */2651+/* */2652+/* result gets the result of multiplying dfl and dfr: */2653+/* dfl is the first decFloat (lhs) */2654+/* dfr is the second decFloat (rhs) */2655+/* set is the context */2656+/* returns result */2657+/* */2658+/* ------------------------------------------------------------------ */2659+decFloat * decFloatMultiply(decFloat *result,2660+ const decFloat *dfl, const decFloat *dfr,2661+ decContext *set) {2662+ bcdnum num; // for final conversion2663+ uByte bcdacc[DECPMAX9*18+1]; // for coefficent in BCD2664+2665+ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) { // either is special?2666+ // NaNs are handled as usual2667+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);2668+ // infinity times zero is bad2669+ if (DFISINF(dfl) && DFISZERO(dfr)) return decInvalid(result, set);2670+ if (DFISINF(dfr) && DFISZERO(dfl)) return decInvalid(result, set);2671+ // both infinite; return canonical infinity with computed sign2672+ DFWORD(result, 0)=DFWORD(dfl, 0)^DFWORD(dfr, 0); // compute sign2673+ return decInfinity(result, result);2674+ }2675+2676+ /* Here when both operands are finite */2677+ decFiniteMultiply(&num, bcdacc, dfl, dfr);2678+ return decFinalize(result, &num, set); // round, check, and lay out2679+ } // decFloatMultiply2680+2681+/* ------------------------------------------------------------------ */2682+/* decFloatNextMinus -- next towards -Infinity */2683+/* */2684+/* result gets the next lesser decFloat */2685+/* dfl is the decFloat to start with */2686+/* set is the context */2687+/* returns result */2688+/* */2689+/* This is 754 nextdown; Invalid is the only status possible (from */2690+/* an sNaN). */2691+/* ------------------------------------------------------------------ */2692+decFloat * decFloatNextMinus(decFloat *result, const decFloat *dfl,2693+ decContext *set) {2694+ decFloat delta; // tiny increment2695+ uInt savestat; // saves status2696+ enum rounding saveround; // .. and mode2697+2698+ // +Infinity is the special case2699+ if (DFISINF(dfl) && !DFISSIGNED(dfl)) {2700+ DFSETNMAX(result);2701+ return result; // [no status to set]2702+ }2703+ // other cases are effected by sutracting a tiny delta -- this2704+ // should be done in a wider format as the delta is unrepresentable2705+ // here (but can be done with normal add if the sign of zero is2706+ // treated carefully, because no Inexactitude is interesting);2707+ // rounding to -Infinity then pushes the result to next below2708+ decFloatZero(&delta); // set up tiny delta2709+ DFWORD(&delta, DECWORDS-1)=1; // coefficient=12710+ DFWORD(&delta, 0)=DECFLOAT_Sign; // Sign=1 + biased exponent=02711+ // set up for the directional round2712+ saveround=set->round; // save mode2713+ set->round=DEC_ROUND_FLOOR; // .. round towards -Infinity2714+ savestat=set->status; // save status2715+ decFloatAdd(result, dfl, &delta, set);2716+ // Add rules mess up the sign when going from +Ntiny to 02717+ if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; // correct2718+ set->status&=DEC_Invalid_operation; // preserve only sNaN status2719+ set->status|=savestat; // restore pending flags2720+ set->round=saveround; // .. and mode2721+ return result;2722+ } // decFloatNextMinus2723+2724+/* ------------------------------------------------------------------ */2725+/* decFloatNextPlus -- next towards +Infinity */2726+/* */2727+/* result gets the next larger decFloat */2728+/* dfl is the decFloat to start with */2729+/* set is the context */2730+/* returns result */2731+/* */2732+/* This is 754 nextup; Invalid is the only status possible (from */2733+/* an sNaN). */2734+/* ------------------------------------------------------------------ */2735+decFloat * decFloatNextPlus(decFloat *result, const decFloat *dfl,2736+ decContext *set) {2737+ uInt savestat; // saves status2738+ enum rounding saveround; // .. and mode2739+ decFloat delta; // tiny increment2740+2741+ // -Infinity is the special case2742+ if (DFISINF(dfl) && DFISSIGNED(dfl)) {2743+ DFSETNMAX(result);2744+ DFWORD(result, 0)|=DECFLOAT_Sign; // make negative2745+ return result; // [no status to set]2746+ }2747+ // other cases are effected by sutracting a tiny delta -- this2748+ // should be done in a wider format as the delta is unrepresentable2749+ // here (but can be done with normal add if the sign of zero is2750+ // treated carefully, because no Inexactitude is interesting);2751+ // rounding to +Infinity then pushes the result to next above2752+ decFloatZero(&delta); // set up tiny delta2753+ DFWORD(&delta, DECWORDS-1)=1; // coefficient=12754+ DFWORD(&delta, 0)=0; // Sign=0 + biased exponent=02755+ // set up for the directional round2756+ saveround=set->round; // save mode2757+ set->round=DEC_ROUND_CEILING; // .. round towards +Infinity2758+ savestat=set->status; // save status2759+ decFloatAdd(result, dfl, &delta, set);2760+ // Add rules mess up the sign when going from -Ntiny to -02761+ if (DFISZERO(result)) DFWORD(result, 0)^=DECFLOAT_Sign; // correct2762+ set->status&=DEC_Invalid_operation; // preserve only sNaN status2763+ set->status|=savestat; // restore pending flags2764+ set->round=saveround; // .. and mode2765+ return result;2766+ } // decFloatNextPlus2767+2768+/* ------------------------------------------------------------------ */2769+/* decFloatNextToward -- next towards a decFloat */2770+/* */2771+/* result gets the next decFloat */2772+/* dfl is the decFloat to start with */2773+/* dfr is the decFloat to move toward */2774+/* set is the context */2775+/* returns result */2776+/* */2777+/* This is 754-1985 nextafter, as modified during revision (dropped */2778+/* from 754-2008); status may be set unless the result is a normal */2779+/* number. */2780+/* ------------------------------------------------------------------ */2781+decFloat * decFloatNextToward(decFloat *result,2782+ const decFloat *dfl, const decFloat *dfr,2783+ decContext *set) {2784+ decFloat delta; // tiny increment or decrement2785+ decFloat pointone; // 1e-12786+ uInt savestat; // saves status2787+ enum rounding saveround; // .. and mode2788+ uInt deltatop; // top word for delta2789+ Int comp; // work2790+2791+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);2792+ // Both are numeric, so Invalid no longer a possibility2793+ comp=decNumCompare(dfl, dfr, 0);2794+ if (comp==0) return decFloatCopySign(result, dfl, dfr); // equal2795+ // unequal; do NextPlus or NextMinus but with different status rules2796+2797+ if (comp<0) { // lhs<rhs, do NextPlus, see above for commentary2798+ if (DFISINF(dfl) && DFISSIGNED(dfl)) { // -Infinity special case2799+ DFSETNMAX(result);2800+ DFWORD(result, 0)|=DECFLOAT_Sign;2801+ return result;2802+ }2803+ saveround=set->round; // save mode2804+ set->round=DEC_ROUND_CEILING; // .. round towards +Infinity2805+ deltatop=0; // positive delta2806+ }2807+ else { // lhs>rhs, do NextMinus, see above for commentary2808+ if (DFISINF(dfl) && !DFISSIGNED(dfl)) { // +Infinity special case2809+ DFSETNMAX(result);2810+ return result;2811+ }2812+ saveround=set->round; // save mode2813+ set->round=DEC_ROUND_FLOOR; // .. round towards -Infinity2814+ deltatop=DECFLOAT_Sign; // negative delta2815+ }2816+ savestat=set->status; // save status2817+ // Here, Inexact is needed where appropriate (and hence Underflow,2818+ // etc.). Therefore the tiny delta which is otherwise2819+ // unrepresentable (see NextPlus and NextMinus) is constructed2820+ // using the multiplication of FMA.2821+ decFloatZero(&delta); // set up tiny delta2822+ DFWORD(&delta, DECWORDS-1)=1; // coefficient=12823+ DFWORD(&delta, 0)=deltatop; // Sign + biased exponent=02824+ decFloatFromString(&pointone, "1E-1", set); // set up multiplier2825+ decFloatFMA(result, &delta, &pointone, dfl, set);2826+ // [Delta is truly tiny, so no need to correct sign of zero]2827+ // use new status unless the result is normal2828+ if (decFloatIsNormal(result)) set->status=savestat; // else goes forward2829+ set->round=saveround; // restore mode2830+ return result;2831+ } // decFloatNextToward2832+2833+/* ------------------------------------------------------------------ */2834+/* decFloatOr -- logical digitwise OR of two decFloats */2835+/* */2836+/* result gets the result of ORing dfl and dfr */2837+/* dfl is the first decFloat (lhs) */2838+/* dfr is the second decFloat (rhs) */2839+/* set is the context */2840+/* returns result, which will be canonical with sign=0 */2841+/* */2842+/* The operands must be positive, finite with exponent q=0, and */2843+/* comprise just zeros and ones; if not, Invalid operation results. */2844+/* ------------------------------------------------------------------ */2845+decFloat * decFloatOr(decFloat *result,2846+ const decFloat *dfl, const decFloat *dfr,2847+ decContext *set) {2848+ if (!DFISUINT01(dfl) || !DFISUINT01(dfr)2849+ || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);2850+ // the operands are positive finite integers (q=0) with just 0s and 1s2851+ #if DOUBLE2852+ DFWORD(result, 0)=ZEROWORD2853+ |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04009124);2854+ DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x49124491;2855+ #elif QUAD2856+ DFWORD(result, 0)=ZEROWORD2857+ |((DFWORD(dfl, 0) | DFWORD(dfr, 0))&0x04000912);2858+ DFWORD(result, 1)=(DFWORD(dfl, 1) | DFWORD(dfr, 1))&0x44912449;2859+ DFWORD(result, 2)=(DFWORD(dfl, 2) | DFWORD(dfr, 2))&0x12449124;2860+ DFWORD(result, 3)=(DFWORD(dfl, 3) | DFWORD(dfr, 3))&0x49124491;2861+ #endif2862+ return result;2863+ } // decFloatOr2864+2865+/* ------------------------------------------------------------------ */2866+/* decFloatPlus -- add value to 0, heeding NaNs, etc. */2867+/* */2868+/* result gets the canonicalized 0+df */2869+/* df is the decFloat to plus */2870+/* set is the context */2871+/* returns result */2872+/* */2873+/* This has the same effect as 0+df where the exponent of the zero is */2874+/* the same as that of df (if df is finite). */2875+/* The effect is also the same as decFloatCopy except that NaNs */2876+/* are handled normally (the sign of a NaN is not affected, and an */2877+/* sNaN will signal), the result is canonical, and zero gets sign 0. */2878+/* ------------------------------------------------------------------ */2879+decFloat * decFloatPlus(decFloat *result, const decFloat *df,2880+ decContext *set) {2881+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set);2882+ decCanonical(result, df); // copy and check2883+ if (DFISZERO(df)) DFBYTE(result, 0)&=~0x80; // turn off sign bit2884+ return result;2885+ } // decFloatPlus2886+2887+/* ------------------------------------------------------------------ */2888+/* decFloatQuantize -- quantize a decFloat */2889+/* */2890+/* result gets the result of quantizing dfl to match dfr */2891+/* dfl is the first decFloat (lhs) */2892+/* dfr is the second decFloat (rhs), which sets the exponent */2893+/* set is the context */2894+/* returns result */2895+/* */2896+/* Unless there is an error or the result is infinite, the exponent */2897+/* of result is guaranteed to be the same as that of dfr. */2898+/* ------------------------------------------------------------------ */2899+decFloat * decFloatQuantize(decFloat *result,2900+ const decFloat *dfl, const decFloat *dfr,2901+ decContext *set) {2902+ Int explb, exprb; // left and right biased exponents2903+ uByte *ulsd; // local LSD pointer2904+ uByte *ub, *uc; // work2905+ Int drop; // ..2906+ uInt dpd; // ..2907+ uInt encode; // encoding accumulator2908+ uInt sourhil, sourhir; // top words from source decFloats2909+ uInt uiwork; // for macros2910+ #if QUAD2911+ uShort uswork; // ..2912+ #endif2913+ // the following buffer holds the coefficient for manipulation2914+ uByte buf[4+DECPMAX*3+2*QUAD]; // + space for zeros to left or right2915+ #if DECTRACE2916+ bcdnum num; // for trace displays2917+ #endif2918+2919+ /* Start decoding the arguments */2920+ sourhil=DFWORD(dfl, 0); // LHS top word2921+ explb=DECCOMBEXP[sourhil>>26]; // get exponent high bits (in place)2922+ sourhir=DFWORD(dfr, 0); // RHS top word2923+ exprb=DECCOMBEXP[sourhir>>26];2924+2925+ if (EXPISSPECIAL(explb | exprb)) { // either is special?2926+ // NaNs are handled as usual2927+ if (DFISNAN(dfl) || DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);2928+ // one infinity but not both is bad2929+ if (DFISINF(dfl)!=DFISINF(dfr)) return decInvalid(result, set);2930+ // both infinite; return canonical infinity with sign of LHS2931+ return decInfinity(result, dfl);2932+ }2933+2934+ /* Here when both arguments are finite */2935+ // complete extraction of the exponents [no need to unbias]2936+ explb+=GETECON(dfl); // + continuation2937+ exprb+=GETECON(dfr); // ..2938+2939+ // calculate the number of digits to drop from the coefficient2940+ drop=exprb-explb; // 0 if nothing to do2941+ if (drop==0) return decCanonical(result, dfl); // return canonical2942+2943+ // the coefficient is needed; lay it out into buf, offset so zeros2944+ // can be added before or after as needed -- an extra heading is2945+ // added so can safely pad Quad DECPMAX-1 zeros to the left by2946+ // fours2947+ #define BUFOFF (buf+4+DECPMAX)2948+ GETCOEFF(dfl, BUFOFF); // decode from decFloat2949+ // [now the msd is at BUFOFF and the lsd is at BUFOFF+DECPMAX-1]2950+2951+ #if DECTRACE2952+ num.msd=BUFOFF;2953+ num.lsd=BUFOFF+DECPMAX-1;2954+ num.exponent=explb-DECBIAS;2955+ num.sign=sourhil & DECFLOAT_Sign;2956+ decShowNum(&num, "dfl");2957+ #endif2958+2959+ if (drop>0) { // [most common case]2960+ // (this code is very similar to that in decFloatFinalize, but2961+ // has many differences so is duplicated here -- so any changes2962+ // may need to be made there, too)2963+ uByte *roundat; // -> re-round digit2964+ uByte reround; // reround value2965+ // printf("Rounding; drop=%ld\n", (LI)drop);2966+2967+ // there is at least one zero needed to the left, in all but one2968+ // exceptional (all-nines) case, so place four zeros now; this is2969+ // needed almost always and makes rounding all-nines by fours safe2970+ UBFROMUI(BUFOFF-4, 0);2971+2972+ // Three cases here:2973+ // 1. new LSD is in coefficient (almost always)2974+ // 2. new LSD is digit to left of coefficient (so MSD is2975+ // round-for-reround digit)2976+ // 3. new LSD is to left of case 2 (whole coefficient is sticky)2977+ // Note that leading zeros can safely be treated as useful digits2978+2979+ // [duplicate check-stickies code to save a test]2980+ // [by-digit check for stickies as runs of zeros are rare]2981+ if (drop<DECPMAX) { // NB lengths not addresses2982+ roundat=BUFOFF+DECPMAX-drop;2983+ reround=*roundat;2984+ for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {2985+ if (*ub!=0) { // non-zero to be discarded2986+ reround=DECSTICKYTAB[reround]; // apply sticky bit2987+ break; // [remainder don't-care]2988+ }2989+ } // check stickies2990+ ulsd=roundat-1; // set LSD2991+ }2992+ else { // edge case2993+ if (drop==DECPMAX) {2994+ roundat=BUFOFF;2995+ reround=*roundat;2996+ }2997+ else {2998+ roundat=BUFOFF-1;2999+ reround=0;3000+ }3001+ for (ub=roundat+1; ub<BUFOFF+DECPMAX; ub++) {3002+ if (*ub!=0) { // non-zero to be discarded3003+ reround=DECSTICKYTAB[reround]; // apply sticky bit3004+ break; // [remainder don't-care]3005+ }3006+ } // check stickies3007+ *BUFOFF=0; // make a coefficient of 03008+ ulsd=BUFOFF; // .. at the MSD place3009+ }3010+3011+ if (reround!=0) { // discarding non-zero3012+ uInt bump=0;3013+ set->status|=DEC_Inexact;3014+3015+ // next decide whether to increment the coefficient3016+ if (set->round==DEC_ROUND_HALF_EVEN) { // fastpath slowest case3017+ if (reround>5) bump=1; // >0.5 goes up3018+ else if (reround==5) // exactly 0.5000 ..3019+ bump=*ulsd & 0x01; // .. up iff [new] lsd is odd3020+ } // r-h-e3021+ else switch (set->round) {3022+ case DEC_ROUND_DOWN: {3023+ // no change3024+ break;} // r-d3025+ case DEC_ROUND_HALF_DOWN: {3026+ if (reround>5) bump=1;3027+ break;} // r-h-d3028+ case DEC_ROUND_HALF_UP: {3029+ if (reround>=5) bump=1;3030+ break;} // r-h-u3031+ case DEC_ROUND_UP: {3032+ if (reround>0) bump=1;3033+ break;} // r-u3034+ case DEC_ROUND_CEILING: {3035+ // same as _UP for positive numbers, and as _DOWN for negatives3036+ if (!(sourhil&DECFLOAT_Sign) && reround>0) bump=1;3037+ break;} // r-c3038+ case DEC_ROUND_FLOOR: {3039+ // same as _UP for negative numbers, and as _DOWN for positive3040+ // [negative reround cannot occur on 0]3041+ if (sourhil&DECFLOAT_Sign && reround>0) bump=1;3042+ break;} // r-f3043+ case DEC_ROUND_05UP: {3044+ if (reround>0) { // anything out there is 'sticky'3045+ // bump iff lsd=0 or 5; this cannot carry so it could be3046+ // effected immediately with no bump -- but the code3047+ // is clearer if this is done the same way as the others3048+ if (*ulsd==0 || *ulsd==5) bump=1;3049+ }3050+ break;} // r-r3051+ default: { // e.g., DEC_ROUND_MAX3052+ set->status|=DEC_Invalid_context;3053+ #if DECCHECK3054+ printf("Unknown rounding mode: %ld\n", (LI)set->round);3055+ #endif3056+ break;}3057+ } // switch (not r-h-e)3058+ // printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump);3059+3060+ if (bump!=0) { // need increment3061+ // increment the coefficient; this could give 1000... (after3062+ // the all nines case)3063+ ub=ulsd;3064+ for (; UBTOUI(ub-3)==0x09090909; ub-=4) UBFROMUI(ub-3, 0);3065+ // now at most 3 digits left to non-9 (usually just the one)3066+ for (; *ub==9; ub--) *ub=0;3067+ *ub+=1;3068+ // [the all-nines case will have carried one digit to the3069+ // left of the original MSD -- just where it is needed]3070+ } // bump needed3071+ } // inexact rounding3072+3073+ // now clear zeros to the left so exactly DECPMAX digits will be3074+ // available in the coefficent -- the first word to the left was3075+ // cleared earlier for safe carry; now add any more needed3076+ if (drop>4) {3077+ UBFROMUI(BUFOFF-8, 0); // must be at least 53078+ for (uc=BUFOFF-12; uc>ulsd-DECPMAX-3; uc-=4) UBFROMUI(uc, 0);3079+ }3080+ } // need round (drop>0)3081+3082+ else { // drop<0; padding with -drop digits is needed3083+ // This is the case where an error can occur if the padded3084+ // coefficient will not fit; checking for this can be done in the3085+ // same loop as padding for zeros if the no-hope and zero cases3086+ // are checked first3087+ if (-drop>DECPMAX-1) { // cannot fit unless 03088+ if (!ISCOEFFZERO(BUFOFF)) return decInvalid(result, set);3089+ // a zero can have any exponent; just drop through and use it3090+ ulsd=BUFOFF+DECPMAX-1;3091+ }3092+ else { // padding will fit (but may still be too long)3093+ // final-word mask depends on endianess3094+ #if DECLITEND3095+ static const uInt dmask[]={0, 0x000000ff, 0x0000ffff, 0x00ffffff};3096+ #else3097+ static const uInt dmask[]={0, 0xff000000, 0xffff0000, 0xffffff00};3098+ #endif3099+ // note that here zeros to the right are added by fours, so in3100+ // the Quad case this could write 36 zeros if the coefficient has3101+ // fewer than three significant digits (hence the +2*QUAD for buf)3102+ for (uc=BUFOFF+DECPMAX;; uc+=4) {3103+ UBFROMUI(uc, 0);3104+ if (UBTOUI(uc-DECPMAX)!=0) { // could be bad3105+ // if all four digits should be zero, definitely bad3106+ if (uc<=BUFOFF+DECPMAX+(-drop)-4)3107+ return decInvalid(result, set);3108+ // must be a 1- to 3-digit sequence; check more carefully3109+ if ((UBTOUI(uc-DECPMAX)&dmask[(-drop)%4])!=0)3110+ return decInvalid(result, set);3111+ break; // no need for loop end test3112+ }3113+ if (uc>=BUFOFF+DECPMAX+(-drop)-4) break; // done3114+ }3115+ ulsd=BUFOFF+DECPMAX+(-drop)-1;3116+ } // pad and check leading zeros3117+ } // drop<03118+3119+ #if DECTRACE3120+ num.msd=ulsd-DECPMAX+1;3121+ num.lsd=ulsd;3122+ num.exponent=explb-DECBIAS;3123+ num.sign=sourhil & DECFLOAT_Sign;3124+ decShowNum(&num, "res");3125+ #endif3126+3127+ /*------------------------------------------------------------------*/3128+ /* At this point the result is DECPMAX digits, ending at ulsd, so */3129+ /* fits the encoding exactly; there is no possibility of error */3130+ /*------------------------------------------------------------------*/3131+ encode=((exprb>>DECECONL)<<4) + *(ulsd-DECPMAX+1); // make index3132+ encode=DECCOMBFROM[encode]; // indexed by (0-2)*16+msd3133+ // the exponent continuation can be extracted from the original RHS3134+ encode|=sourhir & ECONMASK;3135+ encode|=sourhil&DECFLOAT_Sign; // add the sign from LHS3136+3137+ // finally encode the coefficient3138+ // private macro to encode a declet; this version can be used3139+ // because all coefficient digits exist3140+ #define getDPD3q(dpd, n) ub=ulsd-(3*(n))-2; \3141+ dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];3142+3143+ #if DOUBLE3144+ getDPD3q(dpd, 4); encode|=dpd<<8;3145+ getDPD3q(dpd, 3); encode|=dpd>>2;3146+ DFWORD(result, 0)=encode;3147+ encode=dpd<<30;3148+ getDPD3q(dpd, 2); encode|=dpd<<20;3149+ getDPD3q(dpd, 1); encode|=dpd<<10;3150+ getDPD3q(dpd, 0); encode|=dpd;3151+ DFWORD(result, 1)=encode;3152+3153+ #elif QUAD3154+ getDPD3q(dpd,10); encode|=dpd<<4;3155+ getDPD3q(dpd, 9); encode|=dpd>>6;3156+ DFWORD(result, 0)=encode;3157+ encode=dpd<<26;3158+ getDPD3q(dpd, 8); encode|=dpd<<16;3159+ getDPD3q(dpd, 7); encode|=dpd<<6;3160+ getDPD3q(dpd, 6); encode|=dpd>>4;3161+ DFWORD(result, 1)=encode;3162+ encode=dpd<<28;3163+ getDPD3q(dpd, 5); encode|=dpd<<18;3164+ getDPD3q(dpd, 4); encode|=dpd<<8;3165+ getDPD3q(dpd, 3); encode|=dpd>>2;3166+ DFWORD(result, 2)=encode;3167+ encode=dpd<<30;3168+ getDPD3q(dpd, 2); encode|=dpd<<20;3169+ getDPD3q(dpd, 1); encode|=dpd<<10;3170+ getDPD3q(dpd, 0); encode|=dpd;3171+ DFWORD(result, 3)=encode;3172+ #endif3173+ return result;3174+ } // decFloatQuantize3175+3176+/* ------------------------------------------------------------------ */3177+/* decFloatReduce -- reduce finite coefficient to minimum length */3178+/* */3179+/* result gets the reduced decFloat */3180+/* df is the source decFloat */3181+/* set is the context */3182+/* returns result, which will be canonical */3183+/* */3184+/* This removes all possible trailing zeros from the coefficient; */3185+/* some may remain when the number is very close to Nmax. */3186+/* Special values are unchanged and no status is set unless df=sNaN. */3187+/* Reduced zero has an exponent q=0. */3188+/* ------------------------------------------------------------------ */3189+decFloat * decFloatReduce(decFloat *result, const decFloat *df,3190+ decContext *set) {3191+ bcdnum num; // work3192+ uByte buf[DECPMAX], *ub; // coefficient and pointer3193+ if (df!=result) *result=*df; // copy, if needed3194+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set); // sNaN3195+ // zeros and infinites propagate too3196+ if (DFISINF(df)) return decInfinity(result, df); // canonical3197+ if (DFISZERO(df)) {3198+ uInt sign=DFWORD(df, 0)&DECFLOAT_Sign;3199+ decFloatZero(result);3200+ DFWORD(result, 0)|=sign;3201+ return result; // exponent dropped, sign OK3202+ }3203+ // non-zero finite3204+ GETCOEFF(df, buf);3205+ ub=buf+DECPMAX-1; // -> lsd3206+ if (*ub) return result; // no trailing zeros3207+ for (ub--; *ub==0;) ub--; // terminates because non-zero3208+ // *ub is the first non-zero from the right3209+ num.sign=DFWORD(df, 0)&DECFLOAT_Sign; // set up number...3210+ num.exponent=GETEXPUN(df)+(Int)(buf+DECPMAX-1-ub); // adjusted exponent3211+ num.msd=buf;3212+ num.lsd=ub;3213+ return decFinalize(result, &num, set);3214+ } // decFloatReduce3215+3216+/* ------------------------------------------------------------------ */3217+/* decFloatRemainder -- integer divide and return remainder */3218+/* */3219+/* result gets the remainder of dividing dfl by dfr: */3220+/* dfl is the first decFloat (lhs) */3221+/* dfr is the second decFloat (rhs) */3222+/* set is the context */3223+/* returns result */3224+/* */3225+/* ------------------------------------------------------------------ */3226+decFloat * decFloatRemainder(decFloat *result,3227+ const decFloat *dfl, const decFloat *dfr,3228+ decContext *set) {3229+ return decDivide(result, dfl, dfr, set, REMAINDER);3230+ } // decFloatRemainder3231+3232+/* ------------------------------------------------------------------ */3233+/* decFloatRemainderNear -- integer divide to nearest and remainder */3234+/* */3235+/* result gets the remainder of dividing dfl by dfr: */3236+/* dfl is the first decFloat (lhs) */3237+/* dfr is the second decFloat (rhs) */3238+/* set is the context */3239+/* returns result */3240+/* */3241+/* This is the IEEE remainder, where the nearest integer is used. */3242+/* ------------------------------------------------------------------ */3243+decFloat * decFloatRemainderNear(decFloat *result,3244+ const decFloat *dfl, const decFloat *dfr,3245+ decContext *set) {3246+ return decDivide(result, dfl, dfr, set, REMNEAR);3247+ } // decFloatRemainderNear3248+3249+/* ------------------------------------------------------------------ */3250+/* decFloatRotate -- rotate the coefficient of a decFloat left/right */3251+/* */3252+/* result gets the result of rotating dfl */3253+/* dfl is the source decFloat to rotate */3254+/* dfr is the count of digits to rotate, an integer (with q=0) */3255+/* set is the context */3256+/* returns result */3257+/* */3258+/* The digits of the coefficient of dfl are rotated to the left (if */3259+/* dfr is positive) or to the right (if dfr is negative) without */3260+/* adjusting the exponent or the sign of dfl. */3261+/* */3262+/* dfr must be in the range -DECPMAX through +DECPMAX. */3263+/* NaNs are propagated as usual. An infinite dfl is unaffected (but */3264+/* dfr must be valid). No status is set unless dfr is invalid or an */3265+/* operand is an sNaN. The result is canonical. */3266+/* ------------------------------------------------------------------ */3267+#define PHALF (ROUNDUP(DECPMAX/2, 4)) // half length, rounded up3268+decFloat * decFloatRotate(decFloat *result,3269+ const decFloat *dfl, const decFloat *dfr,3270+ decContext *set) {3271+ Int rotate; // dfr as an Int3272+ uByte buf[DECPMAX+PHALF]; // coefficient + half3273+ uInt digits, savestat; // work3274+ bcdnum num; // ..3275+ uByte *ub; // ..3276+3277+ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);3278+ if (!DFISINT(dfr)) return decInvalid(result, set);3279+ digits=decFloatDigits(dfr); // calculate digits3280+ if (digits>2) return decInvalid(result, set); // definitely out of range3281+ rotate=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; // is in bottom declet3282+ if (rotate>DECPMAX) return decInvalid(result, set); // too big3283+ // [from here on no error or status change is possible]3284+ if (DFISINF(dfl)) return decInfinity(result, dfl); // canonical3285+ // handle no-rotate cases3286+ if (rotate==0 || rotate==DECPMAX) return decCanonical(result, dfl);3287+ // a real rotate is needed: 0 < rotate < DECPMAX3288+ // reduce the rotation to no more than half to reduce copying later3289+ // (for QUAD in fact half + 2 digits)3290+ if (DFISSIGNED(dfr)) rotate=-rotate;3291+ if (abs(rotate)>PHALF) {3292+ if (rotate<0) rotate=DECPMAX+rotate;3293+ else rotate=rotate-DECPMAX;3294+ }3295+ // now lay out the coefficient, leaving room to the right or the3296+ // left depending on the direction of rotation3297+ ub=buf;3298+ if (rotate<0) ub+=PHALF; // rotate right, so space to left3299+ GETCOEFF(dfl, ub);3300+ // copy half the digits to left or right, and set num.msd3301+ if (rotate<0) {3302+ memcpy(buf, buf+DECPMAX, PHALF);3303+ num.msd=buf+PHALF+rotate;3304+ }3305+ else {3306+ memcpy(buf+DECPMAX, buf, PHALF);3307+ num.msd=buf+rotate;3308+ }3309+ // fill in rest of num3310+ num.lsd=num.msd+DECPMAX-1;3311+ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;3312+ num.exponent=GETEXPUN(dfl);3313+ savestat=set->status; // record3314+ decFinalize(result, &num, set);3315+ set->status=savestat; // restore3316+ return result;3317+ } // decFloatRotate3318+3319+/* ------------------------------------------------------------------ */3320+/* decFloatSameQuantum -- test decFloats for same quantum */3321+/* */3322+/* dfl is the first decFloat (lhs) */3323+/* dfr is the second decFloat (rhs) */3324+/* returns 1 if the operands have the same quantum, 0 otherwise */3325+/* */3326+/* No error is possible and no status results. */3327+/* ------------------------------------------------------------------ */3328+uInt decFloatSameQuantum(const decFloat *dfl, const decFloat *dfr) {3329+ if (DFISSPECIAL(dfl) || DFISSPECIAL(dfr)) {3330+ if (DFISNAN(dfl) && DFISNAN(dfr)) return 1;3331+ if (DFISINF(dfl) && DFISINF(dfr)) return 1;3332+ return 0; // any other special mixture gives false3333+ }3334+ if (GETEXP(dfl)==GETEXP(dfr)) return 1; // biased exponents match3335+ return 0;3336+ } // decFloatSameQuantum3337+3338+/* ------------------------------------------------------------------ */3339+/* decFloatScaleB -- multiply by a power of 10, as per 754 */3340+/* */3341+/* result gets the result of the operation */3342+/* dfl is the first decFloat (lhs) */3343+/* dfr is the second decFloat (rhs), am integer (with q=0) */3344+/* set is the context */3345+/* returns result */3346+/* */3347+/* This computes result=dfl x 10**dfr where dfr is an integer in the */3348+/* range +/-2*(emax+pmax), typically resulting from LogB. */3349+/* Underflow and Overflow (with Inexact) may occur. NaNs propagate */3350+/* as usual. */3351+/* ------------------------------------------------------------------ */3352+#define SCALEBMAX 2*(DECEMAX+DECPMAX) // D=800, Q=123563353+decFloat * decFloatScaleB(decFloat *result,3354+ const decFloat *dfl, const decFloat *dfr,3355+ decContext *set) {3356+ uInt digits; // work3357+ Int expr; // dfr as an Int3358+3359+ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);3360+ if (!DFISINT(dfr)) return decInvalid(result, set);3361+ digits=decFloatDigits(dfr); // calculate digits3362+3363+ #if DOUBLE3364+ if (digits>3) return decInvalid(result, set); // definitely out of range3365+ expr=DPD2BIN[DFWORD(dfr, 1)&0x3ff]; // must be in bottom declet3366+ #elif QUAD3367+ if (digits>5) return decInvalid(result, set); // definitely out of range3368+ expr=DPD2BIN[DFWORD(dfr, 3)&0x3ff] // in bottom 2 declets ..3369+ +DPD2BIN[(DFWORD(dfr, 3)>>10)&0x3ff]*1000; // ..3370+ #endif3371+ if (expr>SCALEBMAX) return decInvalid(result, set); // oops3372+ // [from now on no error possible]3373+ if (DFISINF(dfl)) return decInfinity(result, dfl); // canonical3374+ if (DFISSIGNED(dfr)) expr=-expr;3375+ // dfl is finite and expr is valid3376+ *result=*dfl; // copy to target3377+ return decFloatSetExponent(result, set, GETEXPUN(result)+expr);3378+ } // decFloatScaleB3379+3380+/* ------------------------------------------------------------------ */3381+/* decFloatShift -- shift the coefficient of a decFloat left or right */3382+/* */3383+/* result gets the result of shifting dfl */3384+/* dfl is the source decFloat to shift */3385+/* dfr is the count of digits to shift, an integer (with q=0) */3386+/* set is the context */3387+/* returns result */3388+/* */3389+/* The digits of the coefficient of dfl are shifted to the left (if */3390+/* dfr is positive) or to the right (if dfr is negative) without */3391+/* adjusting the exponent or the sign of dfl. */3392+/* */3393+/* dfr must be in the range -DECPMAX through +DECPMAX. */3394+/* NaNs are propagated as usual. An infinite dfl is unaffected (but */3395+/* dfr must be valid). No status is set unless dfr is invalid or an */3396+/* operand is an sNaN. The result is canonical. */3397+/* ------------------------------------------------------------------ */3398+decFloat * decFloatShift(decFloat *result,3399+ const decFloat *dfl, const decFloat *dfr,3400+ decContext *set) {3401+ Int shift; // dfr as an Int3402+ uByte buf[DECPMAX*2]; // coefficient + padding3403+ uInt digits, savestat; // work3404+ bcdnum num; // ..3405+ uInt uiwork; // for macros3406+3407+ if (DFISNAN(dfl)||DFISNAN(dfr)) return decNaNs(result, dfl, dfr, set);3408+ if (!DFISINT(dfr)) return decInvalid(result, set);3409+ digits=decFloatDigits(dfr); // calculate digits3410+ if (digits>2) return decInvalid(result, set); // definitely out of range3411+ shift=DPD2BIN[DFWORD(dfr, DECWORDS-1)&0x3ff]; // is in bottom declet3412+ if (shift>DECPMAX) return decInvalid(result, set); // too big3413+ // [from here on no error or status change is possible]3414+3415+ if (DFISINF(dfl)) return decInfinity(result, dfl); // canonical3416+ // handle no-shift and all-shift (clear to zero) cases3417+ if (shift==0) return decCanonical(result, dfl);3418+ if (shift==DECPMAX) { // zero with sign3419+ uByte sign=(uByte)(DFBYTE(dfl, 0)&0x80); // save sign bit3420+ decFloatZero(result); // make +03421+ DFBYTE(result, 0)=(uByte)(DFBYTE(result, 0)|sign); // and set sign3422+ // [cannot safely use CopySign]3423+ return result;3424+ }3425+ // a real shift is needed: 0 < shift < DECPMAX3426+ num.sign=DFWORD(dfl, 0)&DECFLOAT_Sign;3427+ num.exponent=GETEXPUN(dfl);3428+ num.msd=buf;3429+ GETCOEFF(dfl, buf);3430+ if (DFISSIGNED(dfr)) { // shift right3431+ // edge cases are taken care of, so this is easy3432+ num.lsd=buf+DECPMAX-shift-1;3433+ }3434+ else { // shift left -- zero padding needed to right3435+ UBFROMUI(buf+DECPMAX, 0); // 8 will handle most cases3436+ UBFROMUI(buf+DECPMAX+4, 0); // ..3437+ if (shift>8) memset(buf+DECPMAX+8, 0, 8+QUAD*18); // all other cases3438+ num.msd+=shift;3439+ num.lsd=num.msd+DECPMAX-1;3440+ }3441+ savestat=set->status; // record3442+ decFinalize(result, &num, set);3443+ set->status=savestat; // restore3444+ return result;3445+ } // decFloatShift3446+3447+/* ------------------------------------------------------------------ */3448+/* decFloatSubtract -- subtract a decFloat from another */3449+/* */3450+/* result gets the result of subtracting dfr from dfl: */3451+/* dfl is the first decFloat (lhs) */3452+/* dfr is the second decFloat (rhs) */3453+/* set is the context */3454+/* returns result */3455+/* */3456+/* ------------------------------------------------------------------ */3457+decFloat * decFloatSubtract(decFloat *result,3458+ const decFloat *dfl, const decFloat *dfr,3459+ decContext *set) {3460+ decFloat temp;3461+ // NaNs must propagate without sign change3462+ if (DFISNAN(dfr)) return decFloatAdd(result, dfl, dfr, set);3463+ temp=*dfr; // make a copy3464+ DFBYTE(&temp, 0)^=0x80; // flip sign3465+ return decFloatAdd(result, dfl, &temp, set); // and add to the lhs3466+ } // decFloatSubtract3467+3468+/* ------------------------------------------------------------------ */3469+/* decFloatToInt -- round to 32-bit binary integer (4 flavours) */3470+/* */3471+/* df is the decFloat to round */3472+/* set is the context */3473+/* round is the rounding mode to use */3474+/* returns a uInt or an Int, rounded according to the name */3475+/* */3476+/* Invalid will always be signaled if df is a NaN, is Infinite, or is */3477+/* outside the range of the target; Inexact will not be signaled for */3478+/* simple rounding unless 'Exact' appears in the name. */3479+/* ------------------------------------------------------------------ */3480+uInt decFloatToUInt32(const decFloat *df, decContext *set,3481+ enum rounding round) {3482+ return decToInt32(df, set, round, 0, 1);}3483+3484+uInt decFloatToUInt32Exact(const decFloat *df, decContext *set,3485+ enum rounding round) {3486+ return decToInt32(df, set, round, 1, 1);}3487+3488+Int decFloatToInt32(const decFloat *df, decContext *set,3489+ enum rounding round) {3490+ return (Int)decToInt32(df, set, round, 0, 0);}3491+3492+Int decFloatToInt32Exact(const decFloat *df, decContext *set,3493+ enum rounding round) {3494+ return (Int)decToInt32(df, set, round, 1, 0);}3495+3496+/* ------------------------------------------------------------------ */3497+/* decFloatToIntegral -- round to integral value (two flavours) */3498+/* */3499+/* result gets the result */3500+/* df is the decFloat to round */3501+/* set is the context */3502+/* round is the rounding mode to use */3503+/* returns result */3504+/* */3505+/* No exceptions, even Inexact, are raised except for sNaN input, or */3506+/* if 'Exact' appears in the name. */3507+/* ------------------------------------------------------------------ */3508+decFloat * decFloatToIntegralValue(decFloat *result, const decFloat *df,3509+ decContext *set, enum rounding round) {3510+ return decToIntegral(result, df, set, round, 0);}3511+3512+decFloat * decFloatToIntegralExact(decFloat *result, const decFloat *df,3513+ decContext *set) {3514+ return decToIntegral(result, df, set, set->round, 1);}3515+3516+/* ------------------------------------------------------------------ */3517+/* decFloatXor -- logical digitwise XOR of two decFloats */3518+/* */3519+/* result gets the result of XORing dfl and dfr */3520+/* dfl is the first decFloat (lhs) */3521+/* dfr is the second decFloat (rhs) */3522+/* set is the context */3523+/* returns result, which will be canonical with sign=0 */3524+/* */3525+/* The operands must be positive, finite with exponent q=0, and */3526+/* comprise just zeros and ones; if not, Invalid operation results. */3527+/* ------------------------------------------------------------------ */3528+decFloat * decFloatXor(decFloat *result,3529+ const decFloat *dfl, const decFloat *dfr,3530+ decContext *set) {3531+ if (!DFISUINT01(dfl) || !DFISUINT01(dfr)3532+ || !DFISCC01(dfl) || !DFISCC01(dfr)) return decInvalid(result, set);3533+ // the operands are positive finite integers (q=0) with just 0s and 1s3534+ #if DOUBLE3535+ DFWORD(result, 0)=ZEROWORD3536+ |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04009124);3537+ DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x49124491;3538+ #elif QUAD3539+ DFWORD(result, 0)=ZEROWORD3540+ |((DFWORD(dfl, 0) ^ DFWORD(dfr, 0))&0x04000912);3541+ DFWORD(result, 1)=(DFWORD(dfl, 1) ^ DFWORD(dfr, 1))&0x44912449;3542+ DFWORD(result, 2)=(DFWORD(dfl, 2) ^ DFWORD(dfr, 2))&0x12449124;3543+ DFWORD(result, 3)=(DFWORD(dfl, 3) ^ DFWORD(dfr, 3))&0x49124491;3544+ #endif3545+ return result;3546+ } // decFloatXor3547+3548+/* ------------------------------------------------------------------ */3549+/* decInvalid -- set Invalid_operation result */3550+/* */3551+/* result gets a canonical NaN */3552+/* set is the context */3553+/* returns result */3554+/* */3555+/* status has Invalid_operation added */3556+/* ------------------------------------------------------------------ */3557+static decFloat *decInvalid(decFloat *result, decContext *set) {3558+ decFloatZero(result);3559+ DFWORD(result, 0)=DECFLOAT_qNaN;3560+ set->status|=DEC_Invalid_operation;3561+ return result;3562+ } // decInvalid3563+3564+/* ------------------------------------------------------------------ */3565+/* decInfinity -- set canonical Infinity with sign from a decFloat */3566+/* */3567+/* result gets a canonical Infinity */3568+/* df is source decFloat (only the sign is used) */3569+/* returns result */3570+/* */3571+/* df may be the same as result */3572+/* ------------------------------------------------------------------ */3573+static decFloat *decInfinity(decFloat *result, const decFloat *df) {3574+ uInt sign=DFWORD(df, 0); // save source signword3575+ decFloatZero(result); // clear everything3576+ DFWORD(result, 0)=DECFLOAT_Inf | (sign & DECFLOAT_Sign);3577+ return result;3578+ } // decInfinity3579+3580+/* ------------------------------------------------------------------ */3581+/* decNaNs -- handle NaN argument(s) */3582+/* */3583+/* result gets the result of handling dfl and dfr, one or both of */3584+/* which is a NaN */3585+/* dfl is the first decFloat (lhs) */3586+/* dfr is the second decFloat (rhs) -- may be NULL for a single- */3587+/* operand operation */3588+/* set is the context */3589+/* returns result */3590+/* */3591+/* Called when one or both operands is a NaN, and propagates the */3592+/* appropriate result to res. When an sNaN is found, it is changed */3593+/* to a qNaN and Invalid operation is set. */3594+/* ------------------------------------------------------------------ */3595+static decFloat *decNaNs(decFloat *result,3596+ const decFloat *dfl, const decFloat *dfr,3597+ decContext *set) {3598+ // handle sNaNs first3599+ if (dfr!=NULL && DFISSNAN(dfr) && !DFISSNAN(dfl)) dfl=dfr; // use RHS3600+ if (DFISSNAN(dfl)) {3601+ decCanonical(result, dfl); // propagate canonical sNaN3602+ DFWORD(result, 0)&=~(DECFLOAT_qNaN ^ DECFLOAT_sNaN); // quiet3603+ set->status|=DEC_Invalid_operation;3604+ return result;3605+ }3606+ // one or both is a quiet NaN3607+ if (!DFISNAN(dfl)) dfl=dfr; // RHS must be NaN, use it3608+ return decCanonical(result, dfl); // propagate canonical qNaN3609+ } // decNaNs3610+3611+/* ------------------------------------------------------------------ */3612+/* decNumCompare -- numeric comparison of two decFloats */3613+/* */3614+/* dfl is the left-hand decFloat, which is not a NaN */3615+/* dfr is the right-hand decFloat, which is not a NaN */3616+/* tot is 1 for total order compare, 0 for simple numeric */3617+/* returns -1, 0, or +1 for dfl<dfr, dfl=dfr, dfl>dfr */3618+/* */3619+/* No error is possible; status and mode are unchanged. */3620+/* ------------------------------------------------------------------ */3621+static Int decNumCompare(const decFloat *dfl, const decFloat *dfr, Flag tot) {3622+ Int sigl, sigr; // LHS and RHS non-0 signums3623+ Int shift; // shift needed to align operands3624+ uByte *ub, *uc; // work3625+ uInt uiwork; // for macros3626+ // buffers +2 if Quad (36 digits), need double plus 4 for safe padding3627+ uByte bufl[DECPMAX*2+QUAD*2+4]; // for LHS coefficient + padding3628+ uByte bufr[DECPMAX*2+QUAD*2+4]; // for RHS coefficient + padding3629+3630+ sigl=1;3631+ if (DFISSIGNED(dfl)) {3632+ if (!DFISSIGNED(dfr)) { // -LHS +RHS3633+ if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;3634+ return -1; // RHS wins3635+ }3636+ sigl=-1;3637+ }3638+ if (DFISSIGNED(dfr)) {3639+ if (!DFISSIGNED(dfl)) { // +LHS -RHS3640+ if (DFISZERO(dfl) && DFISZERO(dfr) && !tot) return 0;3641+ return +1; // LHS wins3642+ }3643+ }3644+3645+ // signs are the same; operand(s) could be zero3646+ sigr=-sigl; // sign to return if abs(RHS) wins3647+3648+ if (DFISINF(dfl)) {3649+ if (DFISINF(dfr)) return 0; // both infinite & same sign3650+ return sigl; // inf > n3651+ }3652+ if (DFISINF(dfr)) return sigr; // n < inf [dfl is finite]3653+3654+ // here, both are same sign and finite; calculate their offset3655+ shift=GETEXP(dfl)-GETEXP(dfr); // [0 means aligned]3656+ // [bias can be ignored -- the absolute exponent is not relevant]3657+3658+ if (DFISZERO(dfl)) {3659+ if (!DFISZERO(dfr)) return sigr; // LHS=0, RHS!=03660+ // both are zero, return 0 if both same exponent or numeric compare3661+ if (shift==0 || !tot) return 0;3662+ if (shift>0) return sigl;3663+ return sigr; // [shift<0]3664+ }3665+ else { // LHS!=03666+ if (DFISZERO(dfr)) return sigl; // LHS!=0, RHS=03667+ }3668+ // both are known to be non-zero at this point3669+3670+ // if the exponents are so different that the coefficients do not3671+ // overlap (by even one digit) then a full comparison is not needed3672+ if (abs(shift)>=DECPMAX) { // no overlap3673+ // coefficients are known to be non-zero3674+ if (shift>0) return sigl;3675+ return sigr; // [shift<0]3676+ }3677+3678+ // decode the coefficients3679+ // (shift both right two if Quad to make a multiple of four)3680+ #if QUAD3681+ UBFROMUI(bufl, 0);3682+ UBFROMUI(bufr, 0);3683+ #endif3684+ GETCOEFF(dfl, bufl+QUAD*2); // decode from decFloat3685+ GETCOEFF(dfr, bufr+QUAD*2); // ..3686+ if (shift==0) { // aligned; common and easy3687+ // all multiples of four, here3688+ for (ub=bufl, uc=bufr; ub<bufl+DECPMAX+QUAD*2; ub+=4, uc+=4) {3689+ uInt ui=UBTOUI(ub);3690+ if (ui==UBTOUI(uc)) continue; // so far so same3691+ // about to find a winner; go by bytes in case little-endian3692+ for (;; ub++, uc++) {3693+ if (*ub>*uc) return sigl; // difference found3694+ if (*ub<*uc) return sigr; // ..3695+ }3696+ }3697+ } // aligned3698+ else if (shift>0) { // lhs to left3699+ ub=bufl; // RHS pointer3700+ // pad bufl so right-aligned; most shifts will fit in 83701+ UBFROMUI(bufl+DECPMAX+QUAD*2, 0); // add eight zeros3702+ UBFROMUI(bufl+DECPMAX+QUAD*2+4, 0); // ..3703+ if (shift>8) {3704+ // more than eight; fill the rest, and also worth doing the3705+ // lead-in by fours3706+ uByte *up; // work3707+ uByte *upend=bufl+DECPMAX+QUAD*2+shift;3708+ for (up=bufl+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);3709+ // [pads up to 36 in all for Quad]3710+ for (;; ub+=4) {3711+ if (UBTOUI(ub)!=0) return sigl;3712+ if (ub+4>bufl+shift-4) break;3713+ }3714+ }3715+ // check remaining leading digits3716+ for (; ub<bufl+shift; ub++) if (*ub!=0) return sigl;3717+ // now start the overlapped part; bufl has been padded, so the3718+ // comparison can go for the full length of bufr, which is a3719+ // multiple of 4 bytes3720+ for (uc=bufr; ; uc+=4, ub+=4) {3721+ uInt ui=UBTOUI(ub);3722+ if (ui!=UBTOUI(uc)) { // mismatch found3723+ for (;; uc++, ub++) { // check from left [little-endian?]3724+ if (*ub>*uc) return sigl; // difference found3725+ if (*ub<*uc) return sigr; // ..3726+ }3727+ } // mismatch3728+ if (uc==bufr+QUAD*2+DECPMAX-4) break; // all checked3729+ }3730+ } // shift>03731+3732+ else { // shift<0) .. RHS is to left of LHS; mirror shift>03733+ uc=bufr; // RHS pointer3734+ // pad bufr so right-aligned; most shifts will fit in 83735+ UBFROMUI(bufr+DECPMAX+QUAD*2, 0); // add eight zeros3736+ UBFROMUI(bufr+DECPMAX+QUAD*2+4, 0); // ..3737+ if (shift<-8) {3738+ // more than eight; fill the rest, and also worth doing the3739+ // lead-in by fours3740+ uByte *up; // work3741+ uByte *upend=bufr+DECPMAX+QUAD*2-shift;3742+ for (up=bufr+DECPMAX+QUAD*2+8; up<upend; up+=4) UBFROMUI(up, 0);3743+ // [pads up to 36 in all for Quad]3744+ for (;; uc+=4) {3745+ if (UBTOUI(uc)!=0) return sigr;3746+ if (uc+4>bufr-shift-4) break;3747+ }3748+ }3749+ // check remaining leading digits3750+ for (; uc<bufr-shift; uc++) if (*uc!=0) return sigr;3751+ // now start the overlapped part; bufr has been padded, so the3752+ // comparison can go for the full length of bufl, which is a3753+ // multiple of 4 bytes3754+ for (ub=bufl; ; ub+=4, uc+=4) {3755+ uInt ui=UBTOUI(ub);3756+ if (ui!=UBTOUI(uc)) { // mismatch found3757+ for (;; ub++, uc++) { // check from left [little-endian?]3758+ if (*ub>*uc) return sigl; // difference found3759+ if (*ub<*uc) return sigr; // ..3760+ }3761+ } // mismatch3762+ if (ub==bufl+QUAD*2+DECPMAX-4) break; // all checked3763+ }3764+ } // shift<03765+3766+ // Here when compare equal3767+ if (!tot) return 0; // numerically equal3768+ // total ordering .. exponent matters3769+ if (shift>0) return sigl; // total order by exponent3770+ if (shift<0) return sigr; // ..3771+ return 0;3772+ } // decNumCompare3773+3774+/* ------------------------------------------------------------------ */3775+/* decToInt32 -- local routine to effect ToInteger conversions */3776+/* */3777+/* df is the decFloat to convert */3778+/* set is the context */3779+/* rmode is the rounding mode to use */3780+/* exact is 1 if Inexact should be signalled */3781+/* unsign is 1 if the result a uInt, 0 if an Int (cast to uInt) */3782+/* returns 32-bit result as a uInt */3783+/* */3784+/* Invalid is set is df is a NaN, is infinite, or is out-of-range; in */3785+/* these cases 0 is returned. */3786+/* ------------------------------------------------------------------ */3787+static uInt decToInt32(const decFloat *df, decContext *set,3788+ enum rounding rmode, Flag exact, Flag unsign) {3789+ Int exp; // exponent3790+ uInt sourhi, sourpen, sourlo; // top word from source decFloat ..3791+ uInt hi, lo; // .. penultimate, least, etc.3792+ decFloat zero, result; // work3793+ Int i; // ..3794+3795+ /* Start decoding the argument */3796+ sourhi=DFWORD(df, 0); // top word3797+ exp=DECCOMBEXP[sourhi>>26]; // get exponent high bits (in place)3798+ if (EXPISSPECIAL(exp)) { // is special?3799+ set->status|=DEC_Invalid_operation; // signal3800+ return 0;3801+ }3802+3803+ /* Here when the argument is finite */3804+ if (GETEXPUN(df)==0) result=*df; // already a true integer3805+ else { // need to round to integer3806+ enum rounding saveround; // saver3807+ uInt savestatus; // ..3808+ saveround=set->round; // save rounding mode ..3809+ savestatus=set->status; // .. and status3810+ set->round=rmode; // set mode3811+ decFloatZero(&zero); // make 0E+03812+ set->status=0; // clear3813+ decFloatQuantize(&result, df, &zero, set); // [this may fail]3814+ set->round=saveround; // restore rounding mode ..3815+ if (exact) set->status|=savestatus; // include Inexact3816+ else set->status=savestatus; // .. or just original status3817+ }3818+3819+ // only the last four declets of the coefficient can contain3820+ // non-zero; check for others (and also NaN or Infinity from the3821+ // Quantize) first (see DFISZERO for explanation):3822+ // decFloatShow(&result, "sofar");3823+ #if DOUBLE3824+ if ((DFWORD(&result, 0)&0x1c03ff00)!=03825+ || (DFWORD(&result, 0)&0x60000000)==0x60000000) {3826+ #elif QUAD3827+ if ((DFWORD(&result, 2)&0xffffff00)!=03828+ || DFWORD(&result, 1)!=03829+ || (DFWORD(&result, 0)&0x1c003fff)!=03830+ || (DFWORD(&result, 0)&0x60000000)==0x60000000) {3831+ #endif3832+ set->status|=DEC_Invalid_operation; // Invalid or out of range3833+ return 0;3834+ }3835+ // get last twelve digits of the coefficent into hi & ho, base3836+ // 10**9 (see GETCOEFFBILL):3837+ sourlo=DFWORD(&result, DECWORDS-1);3838+ lo=DPD2BIN0[sourlo&0x3ff]3839+ +DPD2BINK[(sourlo>>10)&0x3ff]3840+ +DPD2BINM[(sourlo>>20)&0x3ff];3841+ sourpen=DFWORD(&result, DECWORDS-2);3842+ hi=DPD2BIN0[((sourpen<<2) | (sourlo>>30))&0x3ff];3843+3844+ // according to request, check range carefully3845+ if (unsign) {3846+ if (hi>4 || (hi==4 && lo>294967295) || (hi+lo!=0 && DFISSIGNED(&result))) {3847+ set->status|=DEC_Invalid_operation; // out of range3848+ return 0;3849+ }3850+ return hi*BILLION+lo;3851+ }3852+ // signed3853+ if (hi>2 || (hi==2 && lo>147483647)) {3854+ // handle the usual edge case3855+ if (lo==147483648 && hi==2 && DFISSIGNED(&result)) return 0x80000000;3856+ set->status|=DEC_Invalid_operation; // truly out of range3857+ return 0;3858+ }3859+ i=hi*BILLION+lo;3860+ if (DFISSIGNED(&result)) i=-i;3861+ return (uInt)i;3862+ } // decToInt323863+3864+/* ------------------------------------------------------------------ */3865+/* decToIntegral -- local routine to effect ToIntegral value */3866+/* */3867+/* result gets the result */3868+/* df is the decFloat to round */3869+/* set is the context */3870+/* rmode is the rounding mode to use */3871+/* exact is 1 if Inexact should be signalled */3872+/* returns result */3873+/* ------------------------------------------------------------------ */3874+static decFloat * decToIntegral(decFloat *result, const decFloat *df,3875+ decContext *set, enum rounding rmode,3876+ Flag exact) {3877+ Int exp; // exponent3878+ uInt sourhi; // top word from source decFloat3879+ enum rounding saveround; // saver3880+ uInt savestatus; // ..3881+ decFloat zero; // work3882+3883+ /* Start decoding the argument */3884+ sourhi=DFWORD(df, 0); // top word3885+ exp=DECCOMBEXP[sourhi>>26]; // get exponent high bits (in place)3886+3887+ if (EXPISSPECIAL(exp)) { // is special?3888+ // NaNs are handled as usual3889+ if (DFISNAN(df)) return decNaNs(result, df, NULL, set);3890+ // must be infinite; return canonical infinity with sign of df3891+ return decInfinity(result, df);3892+ }3893+3894+ /* Here when the argument is finite */3895+ // complete extraction of the exponent3896+ exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias3897+3898+ if (exp>=0) return decCanonical(result, df); // already integral3899+3900+ saveround=set->round; // save rounding mode ..3901+ savestatus=set->status; // .. and status3902+ set->round=rmode; // set mode3903+ decFloatZero(&zero); // make 0E+03904+ decFloatQuantize(result, df, &zero, set); // 'integrate'; cannot fail3905+ set->round=saveround; // restore rounding mode ..3906+ if (!exact) set->status=savestatus; // .. and status, unless exact3907+ return result;3908+ } // decToIntegraladded:src/decNumber/decCommon.c+1835 added
1+/* ------------------------------------------------------------------ */2+/* decCommon.c -- common code for all three fixed-size types */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises code that is shared between all the formats */20+/* (decSingle, decDouble, and decQuad); it includes set and extract */21+/* of format components, widening, narrowing, and string conversions. */22+/* */23+/* Unlike decNumber, parameterization takes place at compile time */24+/* rather than at runtime. The parameters are set in the decDouble.c */25+/* (etc.) files, which then include this one to produce the compiled */26+/* code. The functions here, therefore, are code shared between */27+/* multiple formats. */28+/* ------------------------------------------------------------------ */29+// Names here refer to decFloat rather than to decDouble, etc., and30+// the functions are in strict alphabetical order.31+// Constants, tables, and debug function(s) are included only for QUAD32+// (which will always be compiled if DOUBLE or SINGLE are used).33+//34+// Whenever a decContext is used, only the status may be set (using35+// OR) or the rounding mode read; all other fields are ignored and36+// untouched.37+38+// names for simpler testing and default context39+#if DECPMAX==740+ #define SINGLE 141+ #define DOUBLE 042+ #define QUAD 043+ #define DEFCONTEXT DEC_INIT_DECIMAL3244+#elif DECPMAX==1645+ #define SINGLE 046+ #define DOUBLE 147+ #define QUAD 048+ #define DEFCONTEXT DEC_INIT_DECIMAL6449+#elif DECPMAX==3450+ #define SINGLE 051+ #define DOUBLE 052+ #define QUAD 153+ #define DEFCONTEXT DEC_INIT_DECIMAL12854+#else55+ #error Unexpected DECPMAX value56+#endif57+58+/* Assertions */59+60+#if DECPMAX!=7 && DECPMAX!=16 && DECPMAX!=3461+ #error Unexpected Pmax (DECPMAX) value for this module62+#endif63+64+// Assert facts about digit characters, etc.65+#if ('9'&0x0f)!=966+ #error This module assumes characters are of the form 0b....nnnn67+ // where .... are don't care 4 bits and nnnn is 0000 through 100168+#endif69+#if ('9'&0xf0)==('.'&0xf0)70+ #error This module assumes '.' has a different mask than a digit71+#endif72+73+// Assert ToString lay-out conditions74+#if DECSTRING<DECPMAX+975+ #error ToString needs at least 8 characters for lead-in and dot76+#endif77+#if DECPMAX+DECEMAXD+5 > DECSTRING78+ #error Exponent form can be too long for ToString to lay out safely79+#endif80+#if DECEMAXD > 481+ #error Exponent form is too long for ToString to lay out82+ // Note: code for up to 9 digits exists in archives [decOct]83+#endif84+85+/* Private functions used here and possibly in decBasic.c, etc. */86+static decFloat * decFinalize(decFloat *, bcdnum *, decContext *);87+static Flag decBiStr(const char *, const char *, const char *);88+89+/* Macros and private tables; those which are not format-dependent */90+/* are only included if decQuad is being built. */91+92+/* ------------------------------------------------------------------ */93+/* Combination field lookup tables (uInts to save measurable work) */94+/* */95+/* DECCOMBEXP - 2 most-significant-bits of exponent (00, 01, or */96+/* 10), shifted left for format, or DECFLOAT_Inf/NaN */97+/* DECCOMBWEXP - The same, for the next-wider format (unless QUAD) */98+/* DECCOMBMSD - 4-bit most-significant-digit */99+/* [0 if the index is a special (Infinity or NaN)] */100+/* DECCOMBFROM - 5-bit combination field from EXP top bits and MSD */101+/* (placed in uInt so no shift is needed) */102+/* */103+/* DECCOMBEXP, DECCOMBWEXP, and DECCOMBMSD are indexed by the sign */104+/* and 5-bit combination field (0-63, the second half of the table */105+/* identical to the first half) */106+/* DECCOMBFROM is indexed by expTopTwoBits*16 + msd */107+/* */108+/* DECCOMBMSD and DECCOMBFROM are not format-dependent and so are */109+/* only included once, when QUAD is being built */110+/* ------------------------------------------------------------------ */111+static const uInt DECCOMBEXP[64]={112+ 0, 0, 0, 0, 0, 0, 0, 0,113+ 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,114+ 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,115+ 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,116+ 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,117+ 0, 0, 1<<DECECONL, 1<<DECECONL,118+ 2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN,119+ 0, 0, 0, 0, 0, 0, 0, 0,120+ 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,121+ 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,122+ 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,123+ 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,124+ 0, 0, 1<<DECECONL, 1<<DECECONL,125+ 2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN};126+#if !QUAD127+static const uInt DECCOMBWEXP[64]={128+ 0, 0, 0, 0, 0, 0, 0, 0,129+ 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,130+ 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,131+ 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,132+ 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,133+ 0, 0, 1<<DECWECONL, 1<<DECWECONL,134+ 2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN,135+ 0, 0, 0, 0, 0, 0, 0, 0,136+ 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,137+ 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,138+ 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,139+ 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,140+ 0, 0, 1<<DECWECONL, 1<<DECWECONL,141+ 2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN};142+#endif143+144+#if QUAD145+const uInt DECCOMBMSD[64]={146+ 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,147+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0,148+ 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,149+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0};150+151+const uInt DECCOMBFROM[48]={152+ 0x00000000, 0x04000000, 0x08000000, 0x0C000000, 0x10000000, 0x14000000,153+ 0x18000000, 0x1C000000, 0x60000000, 0x64000000, 0x00000000, 0x00000000,154+ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x20000000, 0x24000000,155+ 0x28000000, 0x2C000000, 0x30000000, 0x34000000, 0x38000000, 0x3C000000,156+ 0x68000000, 0x6C000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,157+ 0x00000000, 0x00000000, 0x40000000, 0x44000000, 0x48000000, 0x4C000000,158+ 0x50000000, 0x54000000, 0x58000000, 0x5C000000, 0x70000000, 0x74000000,159+ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000};160+161+/* ------------------------------------------------------------------ */162+/* Request and include the tables to use for conversions */163+/* ------------------------------------------------------------------ */164+#define DEC_BCD2DPD 1 // 0-0x999 -> DPD165+#define DEC_BIN2DPD 1 // 0-999 -> DPD166+#define DEC_BIN2BCD8 1 // 0-999 -> ddd, len167+#define DEC_DPD2BCD8 1 // DPD -> ddd, len168+#define DEC_DPD2BIN 1 // DPD -> 0-999169+#define DEC_DPD2BINK 1 // DPD -> 0-999000170+#define DEC_DPD2BINM 1 // DPD -> 0-999000000171+#include "decDPD.h" // source of the lookup tables172+173+#endif174+175+/* ----------------------------------------------------------------- */176+/* decBiStr -- compare string with pairwise options */177+/* */178+/* targ is the string to compare */179+/* str1 is one of the strings to compare against (length may be 0) */180+/* str2 is the other; it must be the same length as str1 */181+/* */182+/* returns 1 if strings compare equal, (that is, targ is the same */183+/* length as str1 and str2, and each character of targ is in one */184+/* of str1 or str2 in the corresponding position), or 0 otherwise */185+/* */186+/* This is used for generic caseless compare, including the awkward */187+/* case of the Turkish dotted and dotless Is. Use as (for example): */188+/* if (decBiStr(test, "mike", "MIKE")) ... */189+/* ----------------------------------------------------------------- */190+static Flag decBiStr(const char *targ, const char *str1, const char *str2) {191+ for (;;targ++, str1++, str2++) {192+ if (*targ!=*str1 && *targ!=*str2) return 0;193+ // *targ has a match in one (or both, if terminator)194+ if (*targ=='\0') break;195+ } // forever196+ return 1;197+ } // decBiStr198+199+/* ------------------------------------------------------------------ */200+/* decFinalize -- adjust and store a final result */201+/* */202+/* df is the decFloat format number which gets the final result */203+/* num is the descriptor of the number to be checked and encoded */204+/* [its values, including the coefficient, may be modified] */205+/* set is the context to use */206+/* returns df */207+/* */208+/* The num descriptor may point to a bcd8 string of any length; this */209+/* string may have leading insignificant zeros. If it has more than */210+/* DECPMAX digits then the final digit can be a round-for-reround */211+/* digit (i.e., it may include a sticky bit residue). */212+/* */213+/* The exponent (q) may be one of the codes for a special value and */214+/* can be up to 999999999 for conversion from string. */215+/* */216+/* No error is possible, but Inexact, Underflow, and/or Overflow may */217+/* be set. */218+/* ------------------------------------------------------------------ */219+// Constant whose size varies with format; also the check for surprises220+static uByte allnines[DECPMAX]=221+#if SINGLE222+ {9, 9, 9, 9, 9, 9, 9};223+#elif DOUBLE224+ {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};225+#elif QUAD226+ {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,227+ 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};228+#endif229+230+static decFloat * decFinalize(decFloat *df, bcdnum *num,231+ decContext *set) {232+ uByte *ub; // work233+ uInt dpd; // ..234+ uInt uiwork; // for macros235+ uByte *umsd=num->msd; // local copy236+ uByte *ulsd=num->lsd; // ..237+ uInt encode; // encoding accumulator238+ Int length; // coefficient length239+240+ #if DECCHECK241+ Int clen=ulsd-umsd+1;242+ #if QUAD243+ #define COEXTRA 2 // extra-long coefficent244+ #else245+ #define COEXTRA 0246+ #endif247+ if (clen<1 || clen>DECPMAX*3+2+COEXTRA)248+ printf("decFinalize: suspect coefficient [length=%ld]\n", (LI)clen);249+ if (num->sign!=0 && num->sign!=DECFLOAT_Sign)250+ printf("decFinalize: bad sign [%08lx]\n", (LI)num->sign);251+ if (!EXPISSPECIAL(num->exponent)252+ && (num->exponent>1999999999 || num->exponent<-1999999999))253+ printf("decFinalize: improbable exponent [%ld]\n", (LI)num->exponent);254+ // decShowNum(num, "final");255+ #endif256+257+ // A special will have an 'exponent' which is very positive and a258+ // coefficient < DECPMAX259+ length=(uInt)(ulsd-umsd+1); // coefficient length260+261+ if (!NUMISSPECIAL(num)) {262+ Int drop; // digits to be dropped263+ // skip leading insignificant zeros to calculate an exact length264+ // [this is quite expensive]265+ if (*umsd==0) {266+ for (; umsd+3<ulsd && UBTOUI(umsd)==0;) umsd+=4;267+ for (; *umsd==0 && umsd<ulsd;) umsd++;268+ length=ulsd-umsd+1; // recalculate269+ }270+ drop=MAXI(length-DECPMAX, DECQTINY-num->exponent);271+ // drop can now be > digits for bottom-clamp (subnormal) cases272+ if (drop>0) { // rounding needed273+ // (decFloatQuantize has very similar code to this, so any274+ // changes may need to be made there, too)275+ uByte *roundat; // -> re-round digit276+ uByte reround; // reround value277+ // printf("Rounding; drop=%ld\n", (LI)drop);278+279+ num->exponent+=drop; // always update exponent280+281+ // Three cases here:282+ // 1. new LSD is in coefficient (almost always)283+ // 2. new LSD is digit to left of coefficient (so MSD is284+ // round-for-reround digit)285+ // 3. new LSD is to left of case 2 (whole coefficient is sticky)286+ // [duplicate check-stickies code to save a test]287+ // [by-digit check for stickies as runs of zeros are rare]288+ if (drop<length) { // NB lengths not addresses289+ roundat=umsd+length-drop;290+ reround=*roundat;291+ for (ub=roundat+1; ub<=ulsd; ub++) {292+ if (*ub!=0) { // non-zero to be discarded293+ reround=DECSTICKYTAB[reround]; // apply sticky bit294+ break; // [remainder don't-care]295+ }296+ } // check stickies297+ ulsd=roundat-1; // new LSD298+ }299+ else { // edge case300+ if (drop==length) {301+ roundat=umsd;302+ reround=*roundat;303+ }304+ else {305+ roundat=umsd-1;306+ reround=0;307+ }308+ for (ub=roundat+1; ub<=ulsd; ub++) {309+ if (*ub!=0) { // non-zero to be discarded310+ reround=DECSTICKYTAB[reround]; // apply sticky bit311+ break; // [remainder don't-care]312+ }313+ } // check stickies314+ *umsd=0; // coefficient is a 0315+ ulsd=umsd; // ..316+ }317+318+ if (reround!=0) { // discarding non-zero319+ uInt bump=0;320+ set->status|=DEC_Inexact;321+ // if adjusted exponent [exp+digits-1] is < EMIN then num is322+ // subnormal -- so raise Underflow323+ if (num->exponent<DECEMIN && (num->exponent+(ulsd-umsd+1)-1)<DECEMIN)324+ set->status|=DEC_Underflow;325+326+ // next decide whether increment of the coefficient is needed327+ if (set->round==DEC_ROUND_HALF_EVEN) { // fastpath slowest case328+ if (reround>5) bump=1; // >0.5 goes up329+ else if (reround==5) // exactly 0.5000 ..330+ bump=*ulsd & 0x01; // .. up iff [new] lsd is odd331+ } // r-h-e332+ else switch (set->round) {333+ case DEC_ROUND_DOWN: {334+ // no change335+ break;} // r-d336+ case DEC_ROUND_HALF_DOWN: {337+ if (reround>5) bump=1;338+ break;} // r-h-d339+ case DEC_ROUND_HALF_UP: {340+ if (reround>=5) bump=1;341+ break;} // r-h-u342+ case DEC_ROUND_UP: {343+ if (reround>0) bump=1;344+ break;} // r-u345+ case DEC_ROUND_CEILING: {346+ // same as _UP for positive numbers, and as _DOWN for negatives347+ if (!num->sign && reround>0) bump=1;348+ break;} // r-c349+ case DEC_ROUND_FLOOR: {350+ // same as _UP for negative numbers, and as _DOWN for positive351+ // [negative reround cannot occur on 0]352+ if (num->sign && reround>0) bump=1;353+ break;} // r-f354+ case DEC_ROUND_05UP: {355+ if (reround>0) { // anything out there is 'sticky'356+ // bump iff lsd=0 or 5; this cannot carry so it could be357+ // effected immediately with no bump -- but the code358+ // is clearer if this is done the same way as the others359+ if (*ulsd==0 || *ulsd==5) bump=1;360+ }361+ break;} // r-r362+ default: { // e.g., DEC_ROUND_MAX363+ set->status|=DEC_Invalid_context;364+ #if DECCHECK365+ printf("Unknown rounding mode: %ld\n", (LI)set->round);366+ #endif367+ break;}368+ } // switch (not r-h-e)369+ // printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump);370+371+ if (bump!=0) { // need increment372+ // increment the coefficient; this might end up with 1000...373+ // (after the all nines case)374+ ub=ulsd;375+ for(; ub-3>=umsd && UBTOUI(ub-3)==0x09090909; ub-=4) {376+ UBFROMUI(ub-3, 0); // to 00000000377+ }378+ // [note ub could now be to left of msd, and it is not safe379+ // to write to the the left of the msd]380+ // now at most 3 digits left to non-9 (usually just the one)381+ for (; ub>=umsd; *ub=0, ub--) {382+ if (*ub==9) continue; // carry383+ *ub+=1;384+ break;385+ }386+ if (ub<umsd) { // had all-nines387+ *umsd=1; // coefficient to 1000...388+ // usually the 1000... coefficient can be used as-is389+ if ((ulsd-umsd+1)==DECPMAX) {390+ num->exponent++;391+ }392+ else {393+ // if coefficient is shorter than Pmax then num is394+ // subnormal, so extend it; this is safe as drop>0395+ // (or, if the coefficient was supplied above, it could396+ // not be 9); this may make the result normal.397+ ulsd++;398+ *ulsd=0;399+ // [exponent unchanged]400+ #if DECCHECK401+ if (num->exponent!=DECQTINY) // sanity check402+ printf("decFinalize: bad all-nines extend [^%ld, %ld]\n",403+ (LI)num->exponent, (LI)(ulsd-umsd+1));404+ #endif405+ } // subnormal extend406+ } // had all-nines407+ } // bump needed408+ } // inexact rounding409+410+ length=ulsd-umsd+1; // recalculate (may be <DECPMAX)411+ } // need round (drop>0)412+413+ // The coefficient will now fit and has final length unless overflow414+ // decShowNum(num, "rounded");415+416+ // if exponent is >=emax may have to clamp, overflow, or fold-down417+ if (num->exponent>DECEMAX-(DECPMAX-1)) { // is edge case418+ // printf("overflow checks...\n");419+ if (*ulsd==0 && ulsd==umsd) { // have zero420+ num->exponent=DECEMAX-(DECPMAX-1); // clamp to max421+ }422+ else if ((num->exponent+length-1)>DECEMAX) { // > Nmax423+ // Overflow -- these could go straight to encoding, here, but424+ // instead num is adjusted to keep the code cleaner425+ Flag needmax=0; // 1 for finite result426+ set->status|=(DEC_Overflow | DEC_Inexact);427+ switch (set->round) {428+ case DEC_ROUND_DOWN: {429+ needmax=1; // never Infinity430+ break;} // r-d431+ case DEC_ROUND_05UP: {432+ needmax=1; // never Infinity433+ break;} // r-05434+ case DEC_ROUND_CEILING: {435+ if (num->sign) needmax=1; // Infinity iff non-negative436+ break;} // r-c437+ case DEC_ROUND_FLOOR: {438+ if (!num->sign) needmax=1; // Infinity iff negative439+ break;} // r-f440+ default: break; // Infinity in all other cases441+ }442+ if (!needmax) { // easy .. set Infinity443+ num->exponent=DECFLOAT_Inf;444+ *umsd=0; // be clean: coefficient to 0445+ ulsd=umsd; // ..446+ }447+ else { // return Nmax448+ umsd=allnines; // use constant array449+ ulsd=allnines+DECPMAX-1;450+ num->exponent=DECEMAX-(DECPMAX-1);451+ }452+ }453+ else { // no overflow but non-zero and may have to fold-down454+ Int shift=num->exponent-(DECEMAX-(DECPMAX-1));455+ if (shift>0) { // fold-down needed456+ // fold down needed; must copy to buffer in order to pad457+ // with zeros safely; fortunately this is not the worst case458+ // path because cannot have had a round459+ uByte buffer[ROUNDUP(DECPMAX+3, 4)]; // [+3 allows uInt padding]460+ uByte *s=umsd; // source461+ uByte *t=buffer; // safe target462+ uByte *tlsd=buffer+(ulsd-umsd)+shift; // target LSD463+ // printf("folddown shift=%ld\n", (LI)shift);464+ for (; s<=ulsd; s+=4, t+=4) UBFROMUI(t, UBTOUI(s));465+ for (t=tlsd-shift+1; t<=tlsd; t+=4) UBFROMUI(t, 0); // pad 0s466+ num->exponent-=shift;467+ umsd=buffer;468+ ulsd=tlsd;469+ }470+ } // fold-down?471+ length=ulsd-umsd+1; // recalculate length472+ } // high-end edge case473+ } // finite number474+475+ /*------------------------------------------------------------------*/476+ /* At this point the result will properly fit the decFloat */477+ /* encoding, and it can be encoded with no possibility of error */478+ /*------------------------------------------------------------------*/479+ // Following code does not alter coefficient (could be allnines array)480+481+ // fast path possible when DECPMAX digits482+ if (length==DECPMAX) {483+ return decFloatFromBCD(df, num->exponent, umsd, num->sign);484+ } // full-length485+486+ // slower path when not a full-length number; must care about length487+ // [coefficient length here will be < DECPMAX]488+ if (!NUMISSPECIAL(num)) { // is still finite489+ // encode the combination field and exponent continuation490+ uInt uexp=(uInt)(num->exponent+DECBIAS); // biased exponent491+ uInt code=(uexp>>DECECONL)<<4; // top two bits of exp492+ // [msd==0]493+ // look up the combination field and make high word494+ encode=DECCOMBFROM[code]; // indexed by (0-2)*16+msd495+ encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation496+ }497+ else encode=num->exponent; // special [already in word]498+ encode|=num->sign; // add sign499+500+ // private macro to extract a declet, n (where 0<=n<DECLETS and 0501+ // refers to the declet from the least significant three digits)502+ // and put the corresponding DPD code into dpd. Access to umsd and503+ // ulsd (pointers to the most and least significant digit of the504+ // variable-length coefficient) is assumed, along with use of a505+ // working pointer, uInt *ub.506+ // As not full-length then chances are there are many leading zeros507+ // [and there may be a partial triad]508+ #define getDPDt(dpd, n) ub=ulsd-(3*(n))-2; \509+ if (ub<umsd-2) dpd=0; \510+ else if (ub>=umsd) dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)]; \511+ else {dpd=*(ub+2); if (ub+1==umsd) dpd+=*(ub+1)*16; dpd=BCD2DPD[dpd];}512+513+ // place the declets in the encoding words and copy to result (df),514+ // according to endianness; in all cases complete the sign word515+ // first516+ #if DECPMAX==7517+ getDPDt(dpd, 1);518+ encode|=dpd<<10;519+ getDPDt(dpd, 0);520+ encode|=dpd;521+ DFWORD(df, 0)=encode; // just the one word522+523+ #elif DECPMAX==16524+ getDPDt(dpd, 4); encode|=dpd<<8;525+ getDPDt(dpd, 3); encode|=dpd>>2;526+ DFWORD(df, 0)=encode;527+ encode=dpd<<30;528+ getDPDt(dpd, 2); encode|=dpd<<20;529+ getDPDt(dpd, 1); encode|=dpd<<10;530+ getDPDt(dpd, 0); encode|=dpd;531+ DFWORD(df, 1)=encode;532+533+ #elif DECPMAX==34534+ getDPDt(dpd,10); encode|=dpd<<4;535+ getDPDt(dpd, 9); encode|=dpd>>6;536+ DFWORD(df, 0)=encode;537+538+ encode=dpd<<26;539+ getDPDt(dpd, 8); encode|=dpd<<16;540+ getDPDt(dpd, 7); encode|=dpd<<6;541+ getDPDt(dpd, 6); encode|=dpd>>4;542+ DFWORD(df, 1)=encode;543+544+ encode=dpd<<28;545+ getDPDt(dpd, 5); encode|=dpd<<18;546+ getDPDt(dpd, 4); encode|=dpd<<8;547+ getDPDt(dpd, 3); encode|=dpd>>2;548+ DFWORD(df, 2)=encode;549+550+ encode=dpd<<30;551+ getDPDt(dpd, 2); encode|=dpd<<20;552+ getDPDt(dpd, 1); encode|=dpd<<10;553+ getDPDt(dpd, 0); encode|=dpd;554+ DFWORD(df, 3)=encode;555+ #endif556+557+ // printf("Status: %08lx\n", (LI)set->status);558+ // decFloatShow(df, "final2");559+ return df;560+ } // decFinalize561+562+/* ------------------------------------------------------------------ */563+/* decFloatFromBCD -- set decFloat from exponent, BCD8, and sign */564+/* */565+/* df is the target decFloat */566+/* exp is the in-range unbiased exponent, q, or a special value in */567+/* the form returned by decFloatGetExponent */568+/* bcdar holds DECPMAX digits to set the coefficient from, one */569+/* digit in each byte (BCD8 encoding); the first (MSD) is ignored */570+/* if df is a NaN; all are ignored if df is infinite. */571+/* All bytes must be in 0-9; results are undefined otherwise. */572+/* sig is DECFLOAT_Sign to set the sign bit, 0 otherwise */573+/* returns df, which will be canonical */574+/* */575+/* No error is possible, and no status will be set. */576+/* ------------------------------------------------------------------ */577+decFloat * decFloatFromBCD(decFloat *df, Int exp, const uByte *bcdar,578+ Int sig) {579+ uInt encode, dpd; // work580+ const uByte *ub; // ..581+582+ if (EXPISSPECIAL(exp)) encode=exp|sig;// specials already encoded583+ else { // is finite584+ // encode the combination field and exponent continuation585+ uInt uexp=(uInt)(exp+DECBIAS); // biased exponent586+ uInt code=(uexp>>DECECONL)<<4; // top two bits of exp587+ code+=bcdar[0]; // add msd588+ // look up the combination field and make high word589+ encode=DECCOMBFROM[code]|sig; // indexed by (0-2)*16+msd590+ encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation591+ }592+593+ // private macro to extract a declet, n (where 0<=n<DECLETS and 0594+ // refers to the declet from the least significant three digits)595+ // and put the corresponding DPD code into dpd.596+ // Use of a working pointer, uInt *ub, is assumed.597+598+ #define getDPDb(dpd, n) ub=bcdar+DECPMAX-1-(3*(n))-2; \599+ dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];600+601+ // place the declets in the encoding words and copy to result (df),602+ // according to endianness; in all cases complete the sign word603+ // first604+ #if DECPMAX==7605+ getDPDb(dpd, 1);606+ encode|=dpd<<10;607+ getDPDb(dpd, 0);608+ encode|=dpd;609+ DFWORD(df, 0)=encode; // just the one word610+611+ #elif DECPMAX==16612+ getDPDb(dpd, 4); encode|=dpd<<8;613+ getDPDb(dpd, 3); encode|=dpd>>2;614+ DFWORD(df, 0)=encode;615+ encode=dpd<<30;616+ getDPDb(dpd, 2); encode|=dpd<<20;617+ getDPDb(dpd, 1); encode|=dpd<<10;618+ getDPDb(dpd, 0); encode|=dpd;619+ DFWORD(df, 1)=encode;620+621+ #elif DECPMAX==34622+ getDPDb(dpd,10); encode|=dpd<<4;623+ getDPDb(dpd, 9); encode|=dpd>>6;624+ DFWORD(df, 0)=encode;625+626+ encode=dpd<<26;627+ getDPDb(dpd, 8); encode|=dpd<<16;628+ getDPDb(dpd, 7); encode|=dpd<<6;629+ getDPDb(dpd, 6); encode|=dpd>>4;630+ DFWORD(df, 1)=encode;631+632+ encode=dpd<<28;633+ getDPDb(dpd, 5); encode|=dpd<<18;634+ getDPDb(dpd, 4); encode|=dpd<<8;635+ getDPDb(dpd, 3); encode|=dpd>>2;636+ DFWORD(df, 2)=encode;637+638+ encode=dpd<<30;639+ getDPDb(dpd, 2); encode|=dpd<<20;640+ getDPDb(dpd, 1); encode|=dpd<<10;641+ getDPDb(dpd, 0); encode|=dpd;642+ DFWORD(df, 3)=encode;643+ #endif644+ // decFloatShow(df, "fromB");645+ return df;646+ } // decFloatFromBCD647+648+/* ------------------------------------------------------------------ */649+/* decFloatFromPacked -- set decFloat from exponent and packed BCD */650+/* */651+/* df is the target decFloat */652+/* exp is the in-range unbiased exponent, q, or a special value in */653+/* the form returned by decFloatGetExponent */654+/* packed holds DECPMAX packed decimal digits plus a sign nibble */655+/* (all 6 codes are OK); the first (MSD) is ignored if df is a NaN */656+/* and all except sign are ignored if df is infinite. For DOUBLE */657+/* and QUAD the first (pad) nibble is also ignored in all cases. */658+/* All coefficient nibbles must be in 0-9 and sign in A-F; results */659+/* are undefined otherwise. */660+/* returns df, which will be canonical */661+/* */662+/* No error is possible, and no status will be set. */663+/* ------------------------------------------------------------------ */664+decFloat * decFloatFromPacked(decFloat *df, Int exp, const uByte *packed) {665+ uByte bcdar[DECPMAX+2]; // work [+1 for pad, +1 for sign]666+ const uByte *ip; // ..667+ uByte *op; // ..668+ Int sig=0; // sign669+670+ // expand coefficient and sign to BCDAR671+ #if SINGLE672+ op=bcdar+1; // no pad digit673+ #else674+ op=bcdar; // first (pad) digit ignored675+ #endif676+ for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {677+ *op++=*ip>>4;678+ *op++=(uByte)(*ip&0x0f); // [final nibble is sign]679+ }680+ op--; // -> sign byte681+ if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;682+683+ if (EXPISSPECIAL(exp)) { // Infinity or NaN684+ if (!EXPISINF(exp)) bcdar[1]=0; // a NaN: ignore MSD685+ else memset(bcdar+1, 0, DECPMAX); // Infinite: coefficient to 0686+ }687+ return decFloatFromBCD(df, exp, bcdar+1, sig);688+ } // decFloatFromPacked689+690+/* ------------------------------------------------------------------ */691+/* decFloatFromPackedChecked -- set from exponent and packed; checked */692+/* */693+/* df is the target decFloat */694+/* exp is the in-range unbiased exponent, q, or a special value in */695+/* the form returned by decFloatGetExponent */696+/* packed holds DECPMAX packed decimal digits plus a sign nibble */697+/* (all 6 codes are OK); the first (MSD) must be 0 if df is a NaN */698+/* and all digits must be 0 if df is infinite. For DOUBLE and */699+/* QUAD the first (pad) nibble must be 0. */700+/* All coefficient nibbles must be in 0-9 and sign in A-F. */701+/* returns df, which will be canonical or NULL if any of the */702+/* requirements are not met (if this case df is unchanged); that */703+/* is, the input data must be as returned by decFloatToPacked, */704+/* except that all six sign codes are acccepted. */705+/* */706+/* No status will be set. */707+/* ------------------------------------------------------------------ */708+decFloat * decFloatFromPackedChecked(decFloat *df, Int exp,709+ const uByte *packed) {710+ uByte bcdar[DECPMAX+2]; // work [+1 for pad, +1 for sign]711+ const uByte *ip; // ..712+ uByte *op; // ..713+ Int sig=0; // sign714+715+ // expand coefficient and sign to BCDAR716+ #if SINGLE717+ op=bcdar+1; // no pad digit718+ #else719+ op=bcdar; // first (pad) digit here720+ #endif721+ for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {722+ *op=*ip>>4;723+ if (*op>9) return NULL;724+ op++;725+ *op=(uByte)(*ip&0x0f); // [final nibble is sign]726+ if (*op>9 && ip<packed+((DECPMAX+2)/2)-1) return NULL;727+ op++;728+ }729+ op--; // -> sign byte730+ if (*op<=9) return NULL; // bad sign731+ if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;732+733+ #if !SINGLE734+ if (bcdar[0]!=0) return NULL; // bad pad nibble735+ #endif736+737+ if (EXPISNAN(exp)) { // a NaN738+ if (bcdar[1]!=0) return NULL; // bad msd739+ } // NaN740+ else if (EXPISINF(exp)) { // is infinite741+ Int i;742+ for (i=0; i<DECPMAX; i++) {743+ if (bcdar[i+1]!=0) return NULL; // should be all zeros744+ }745+ } // infinity746+ else { // finite747+ // check the exponent is in range748+ if (exp>DECEMAX-DECPMAX+1) return NULL;749+ if (exp<DECEMIN-DECPMAX+1) return NULL;750+ }751+ return decFloatFromBCD(df, exp, bcdar+1, sig);752+ } // decFloatFromPacked753+754+/* ------------------------------------------------------------------ */755+/* decFloatFromString -- conversion from numeric string */756+/* */757+/* result is the decFloat format number which gets the result of */758+/* the conversion */759+/* *string is the character string which should contain a valid */760+/* number (which may be a special value), \0-terminated */761+/* If there are too many significant digits in the */762+/* coefficient it will be rounded. */763+/* set is the context */764+/* returns result */765+/* */766+/* The length of the coefficient and the size of the exponent are */767+/* checked by this routine, so the correct error (Underflow or */768+/* Overflow) can be reported or rounding applied, as necessary. */769+/* */770+/* There is no limit to the coefficient length for finite inputs; */771+/* NaN payloads must be integers with no more than DECPMAX-1 digits. */772+/* Exponents may have up to nine significant digits. */773+/* */774+/* If bad syntax is detected, the result will be a quiet NaN. */775+/* ------------------------------------------------------------------ */776+decFloat * decFloatFromString(decFloat *result, const char *string,777+ decContext *set) {778+ Int digits; // count of digits in coefficient779+ const char *dotchar=NULL; // where dot was found [NULL if none]780+ const char *cfirst=string; // -> first character of decimal part781+ const char *c; // work782+ uByte *ub; // ..783+ uInt uiwork; // for macros784+ bcdnum num; // collects data for finishing785+ uInt error=DEC_Conversion_syntax; // assume the worst786+ uByte buffer[ROUNDUP(DECSTRING+11, 8)]; // room for most coefficents,787+ // some common rounding, +3, & pad788+ #if DECTRACE789+ // printf("FromString %s ...\n", string);790+ #endif791+792+ for(;;) { // once-only 'loop'793+ num.sign=0; // assume non-negative794+ num.msd=buffer; // MSD is here always795+796+ // detect and validate the coefficient, including any leading,797+ // trailing, or embedded '.'798+ // [could test four-at-a-time here (saving 10% for decQuads),799+ // but that risks storage violation because the position of the800+ // terminator is unknown]801+ for (c=string;; c++) { // -> input character802+ if (((unsigned)(*c-'0'))<=9) continue; // '0' through '9' is good803+ if (*c=='\0') break; // most common non-digit804+ if (*c=='.') {805+ if (dotchar!=NULL) break; // not first '.'806+ dotchar=c; // record offset into decimal part807+ continue;}808+ if (c==string) { // first in string...809+ if (*c=='-') { // valid - sign810+ cfirst++;811+ num.sign=DECFLOAT_Sign;812+ continue;}813+ if (*c=='+') { // valid + sign814+ cfirst++;815+ continue;}816+ }817+ // *c is not a digit, terminator, or a valid +, -, or '.'818+ break;819+ } // c loop820+821+ digits=(uInt)(c-cfirst); // digits (+1 if a dot)822+823+ if (digits>0) { // had digits and/or dot824+ const char *clast=c-1; // note last coefficient char position825+ Int exp=0; // exponent accumulator826+ if (*c!='\0') { // something follows the coefficient827+ uInt edig; // unsigned work828+ // had some digits and more to come; expect E[+|-]nnn now829+ const char *firstexp; // exponent first non-zero830+ if (*c!='E' && *c!='e') break;831+ c++; // to (optional) sign832+ if (*c=='-' || *c=='+') c++; // step over sign (c=clast+2)833+ if (*c=='\0') break; // no digits! (e.g., '1.2E')834+ for (; *c=='0';) c++; // skip leading zeros [even last]835+ firstexp=c; // remember start [maybe '\0']836+ // gather exponent digits837+ edig=(uInt)*c-(uInt)'0';838+ if (edig<=9) { // [check not bad or terminator]839+ exp+=edig; // avoid initial X10840+ c++;841+ for (;; c++) {842+ edig=(uInt)*c-(uInt)'0';843+ if (edig>9) break;844+ exp=exp*10+edig;845+ }846+ }847+ // if not now on the '\0', *c must not be a digit848+ if (*c!='\0') break;849+850+ // (this next test must be after the syntax checks)851+ // if definitely more than the possible digits for format then852+ // the exponent may have wrapped, so simply set it to a certain853+ // over/underflow value854+ if (c>firstexp+DECEMAXD) exp=DECEMAX*2;855+ if (*(clast+2)=='-') exp=-exp; // was negative856+ } // exponent part857+858+ if (dotchar!=NULL) { // had a '.'859+ digits--; // remove from digits count860+ if (digits==0) break; // was dot alone: bad syntax861+ exp-=(Int)(clast-dotchar); // adjust exponent862+ // [the '.' can now be ignored]863+ }864+ num.exponent=exp; // exponent is good; store it865+866+ // Here when whole string has been inspected and syntax is good867+ // cfirst->first digit or dot, clast->last digit or dot868+ error=0; // no error possible now869+870+ // if the number of digits in the coefficient will fit in buffer871+ // then it can simply be converted to bcd8 and copied -- decFinalize872+ // will take care of leading zeros and rounding; the buffer is big873+ // enough for all canonical coefficients, including 0.00000nn...874+ ub=buffer;875+ if (digits<=(Int)(sizeof(buffer)-3)) { // [-3 allows by-4s copy]876+ c=cfirst;877+ if (dotchar!=NULL) { // a dot to worry about878+ if (*(c+1)=='.') { // common canonical case879+ *ub++=(uByte)(*c-'0'); // copy leading digit880+ c+=2; // prepare to handle rest881+ }882+ else for (; c<=clast;) { // '.' could be anywhere883+ // as usual, go by fours when safe; NB it has been asserted884+ // that a '.' does not have the same mask as a digit885+ if (c<=clast-3 // safe for four886+ && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // test four887+ UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f); // to BCD8888+ ub+=4;889+ c+=4;890+ continue;891+ }892+ if (*c=='.') { // found the dot893+ c++; // step over it ..894+ break; // .. and handle the rest895+ }896+ *ub++=(uByte)(*c++-'0');897+ }898+ } // had dot899+ // Now no dot; do this by fours (where safe)900+ for (; c<=clast-3; c+=4, ub+=4) UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f);901+ for (; c<=clast; c++, ub++) *ub=(uByte)(*c-'0');902+ num.lsd=buffer+digits-1; // record new LSD903+ } // fits904+905+ else { // too long for buffer906+ // [This is a rare and unusual case; arbitrary-length input]907+ // strip leading zeros [but leave final 0 if all 0's]908+ if (*cfirst=='.') cfirst++; // step past dot at start909+ if (*cfirst=='0') { // [cfirst always -> digit]910+ for (; cfirst<clast; cfirst++) {911+ if (*cfirst!='0') { // non-zero found912+ if (*cfirst=='.') continue; // [ignore]913+ break; // done914+ }915+ digits--; // 0 stripped916+ } // cfirst917+ } // at least one leading 0918+919+ // the coefficient is now as short as possible, but may still920+ // be too long; copy up to Pmax+1 digits to the buffer, then921+ // just record any non-zeros (set round-for-reround digit)922+ for (c=cfirst; c<=clast && ub<=buffer+DECPMAX; c++) {923+ // (see commentary just above)924+ if (c<=clast-3 // safe for four925+ && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // four digits926+ UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f); // to BCD8927+ ub+=4;928+ c+=3; // [will become 4]929+ continue;930+ }931+ if (*c=='.') continue; // [ignore]932+ *ub++=(uByte)(*c-'0');933+ }934+ ub--; // -> LSD935+ for (; c<=clast; c++) { // inspect remaining chars936+ if (*c!='0') { // sticky bit needed937+ if (*c=='.') continue; // [ignore]938+ *ub=DECSTICKYTAB[*ub]; // update round-for-reround939+ break; // no need to look at more940+ }941+ }942+ num.lsd=ub; // record LSD943+ // adjust exponent for dropped digits944+ num.exponent+=digits-(Int)(ub-buffer+1);945+ } // too long for buffer946+ } // digits and/or dot947+948+ else { // no digits or dot were found949+ // only Infinities and NaNs are allowed, here950+ if (*c=='\0') break; // nothing there is bad951+ buffer[0]=0; // default a coefficient of 0952+ num.lsd=buffer; // ..953+ if (decBiStr(c, "infinity", "INFINITY")954+ || decBiStr(c, "inf", "INF")) num.exponent=DECFLOAT_Inf;955+ else { // should be a NaN956+ num.exponent=DECFLOAT_qNaN; // assume quiet NaN957+ if (*c=='s' || *c=='S') { // probably an sNaN958+ num.exponent=DECFLOAT_sNaN; // effect the 's'959+ c++; // and step over it960+ }961+ if (*c!='N' && *c!='n') break; // check caseless "NaN"962+ c++;963+ if (*c!='a' && *c!='A') break; // ..964+ c++;965+ if (*c!='N' && *c!='n') break; // ..966+ c++;967+ // now either nothing, or nnnn payload (no dots), expected968+ // -> start of integer, and skip leading 0s [including plain 0]969+ for (cfirst=c; *cfirst=='0';) cfirst++;970+ if (*cfirst!='\0') { // not empty or all-0, payload971+ // payload found; check all valid digits and copy to buffer as bcd8972+ ub=buffer;973+ for (c=cfirst;; c++, ub++) {974+ if ((unsigned)(*c-'0')>9) break; // quit if not 0-9975+ if (c-cfirst==DECPMAX-1) break; // too many digits976+ *ub=(uByte)(*c-'0'); // good bcd8977+ }978+ if (*c!='\0') break; // not all digits, or too many979+ num.lsd=ub-1; // record new LSD980+ }981+ } // NaN or sNaN982+ error=0; // syntax is OK983+ } // digits=0 (special expected)984+ break; // drop out985+ } // [for(;;) once-loop]986+987+ // decShowNum(&num, "fromStr");988+989+ if (error!=0) {990+ set->status|=error;991+ num.exponent=DECFLOAT_qNaN; // set up quiet NaN992+ num.sign=0; // .. with 0 sign993+ buffer[0]=0; // .. and coefficient994+ num.lsd=buffer; // ..995+ // decShowNum(&num, "oops");996+ }997+998+ // decShowNum(&num, "dffs");999+ decFinalize(result, &num, set); // round, check, and lay out1000+ // decFloatShow(result, "fromString");1001+ return result;1002+ } // decFloatFromString1003+1004+/* ------------------------------------------------------------------ */1005+/* decFloatFromWider -- conversion from next-wider format */1006+/* */1007+/* result is the decFloat format number which gets the result of */1008+/* the conversion */1009+/* wider is the decFloatWider format number which will be narrowed */1010+/* set is the context */1011+/* returns result */1012+/* */1013+/* Narrowing can cause rounding, overflow, etc., but not Invalid */1014+/* operation (sNaNs are copied and do not signal). */1015+/* ------------------------------------------------------------------ */1016+// narrow-to is not possible for decQuad format numbers; simply omit1017+#if !QUAD1018+decFloat * decFloatFromWider(decFloat *result, const decFloatWider *wider,1019+ decContext *set) {1020+ bcdnum num; // collects data for finishing1021+ uByte bcdar[DECWPMAX]; // room for wider coefficient1022+ uInt widerhi=DFWWORD(wider, 0); // top word1023+ Int exp;1024+1025+ GETWCOEFF(wider, bcdar);1026+1027+ num.msd=bcdar; // MSD is here always1028+ num.lsd=bcdar+DECWPMAX-1; // LSD is here always1029+ num.sign=widerhi&0x80000000; // extract sign [DECFLOAT_Sign=Neg]1030+1031+ // decode the wider combination field to exponent1032+ exp=DECCOMBWEXP[widerhi>>26]; // decode from wider combination field1033+ // if it is a special there's nothing to do unless sNaN; if it's1034+ // finite then add the (wider) exponent continuation and unbias1035+ if (EXPISSPECIAL(exp)) exp=widerhi&0x7e000000; // include sNaN selector1036+ else exp+=GETWECON(wider)-DECWBIAS;1037+ num.exponent=exp;1038+1039+ // decShowNum(&num, "dffw");1040+ return decFinalize(result, &num, set);// round, check, and lay out1041+ } // decFloatFromWider1042+#endif1043+1044+/* ------------------------------------------------------------------ */1045+/* decFloatGetCoefficient -- get coefficient as BCD8 */1046+/* */1047+/* df is the decFloat from which to extract the coefficient */1048+/* bcdar is where DECPMAX bytes will be written, one BCD digit in */1049+/* each byte (BCD8 encoding); if df is a NaN the first byte will */1050+/* be zero, and if it is infinite they will all be zero */1051+/* returns the sign of the coefficient (DECFLOAT_Sign if negative, */1052+/* 0 otherwise) */1053+/* */1054+/* No error is possible, and no status will be set. If df is a */1055+/* special value the array is set to zeros (for Infinity) or to the */1056+/* payload of a qNaN or sNaN. */1057+/* ------------------------------------------------------------------ */1058+Int decFloatGetCoefficient(const decFloat *df, uByte *bcdar) {1059+ if (DFISINF(df)) memset(bcdar, 0, DECPMAX);1060+ else {1061+ GETCOEFF(df, bcdar); // use macro1062+ if (DFISNAN(df)) bcdar[0]=0; // MSD needs correcting1063+ }1064+ return GETSIGN(df);1065+ } // decFloatGetCoefficient1066+1067+/* ------------------------------------------------------------------ */1068+/* decFloatGetExponent -- get unbiased exponent */1069+/* */1070+/* df is the decFloat from which to extract the exponent */1071+/* returns the exponent, q. */1072+/* */1073+/* No error is possible, and no status will be set. If df is a */1074+/* special value the first seven bits of the decFloat are returned, */1075+/* left adjusted and with the first (sign) bit set to 0 (followed by */1076+/* 25 0 bits). e.g., -sNaN would return 0x7e000000 (DECFLOAT_sNaN). */1077+/* ------------------------------------------------------------------ */1078+Int decFloatGetExponent(const decFloat *df) {1079+ if (DFISSPECIAL(df)) return DFWORD(df, 0)&0x7e000000;1080+ return GETEXPUN(df);1081+ } // decFloatGetExponent1082+1083+/* ------------------------------------------------------------------ */1084+/* decFloatSetCoefficient -- set coefficient from BCD8 */1085+/* */1086+/* df is the target decFloat (and source of exponent/special value) */1087+/* bcdar holds DECPMAX digits to set the coefficient from, one */1088+/* digit in each byte (BCD8 encoding); the first (MSD) is ignored */1089+/* if df is a NaN; all are ignored if df is infinite. */1090+/* sig is DECFLOAT_Sign to set the sign bit, 0 otherwise */1091+/* returns df, which will be canonical */1092+/* */1093+/* No error is possible, and no status will be set. */1094+/* ------------------------------------------------------------------ */1095+decFloat * decFloatSetCoefficient(decFloat *df, const uByte *bcdar,1096+ Int sig) {1097+ uInt exp; // for exponent1098+ uByte bcdzero[DECPMAX]; // for infinities1099+1100+ // Exponent/special code is extracted from df1101+ if (DFISSPECIAL(df)) {1102+ exp=DFWORD(df, 0)&0x7e000000;1103+ if (DFISINF(df)) {1104+ memset(bcdzero, 0, DECPMAX);1105+ return decFloatFromBCD(df, exp, bcdzero, sig);1106+ }1107+ }1108+ else exp=GETEXPUN(df);1109+ return decFloatFromBCD(df, exp, bcdar, sig);1110+ } // decFloatSetCoefficient1111+1112+/* ------------------------------------------------------------------ */1113+/* decFloatSetExponent -- set exponent or special value */1114+/* */1115+/* df is the target decFloat (and source of coefficient/payload) */1116+/* set is the context for reporting status */1117+/* exp is the unbiased exponent, q, or a special value in the form */1118+/* returned by decFloatGetExponent */1119+/* returns df, which will be canonical */1120+/* */1121+/* No error is possible, but Overflow or Underflow might occur. */1122+/* ------------------------------------------------------------------ */1123+decFloat * decFloatSetExponent(decFloat *df, decContext *set, Int exp) {1124+ uByte bcdcopy[DECPMAX]; // for coefficient1125+ bcdnum num; // work1126+ num.exponent=exp;1127+ num.sign=decFloatGetCoefficient(df, bcdcopy); // extract coefficient1128+ if (DFISSPECIAL(df)) { // MSD or more needs correcting1129+ if (DFISINF(df)) memset(bcdcopy, 0, DECPMAX);1130+ bcdcopy[0]=0;1131+ }1132+ num.msd=bcdcopy;1133+ num.lsd=bcdcopy+DECPMAX-1;1134+ return decFinalize(df, &num, set);1135+ } // decFloatSetExponent1136+1137+/* ------------------------------------------------------------------ */1138+/* decFloatRadix -- returns the base (10) */1139+/* */1140+/* df is any decFloat of this format */1141+/* ------------------------------------------------------------------ */1142+uInt decFloatRadix(const decFloat *df) {1143+ if (df) return 10; // to placate compiler1144+ return 10;1145+ } // decFloatRadix1146+1147+/* The following function is not available if DECPRINT=0 */1148+#if DECPRINT1149+/* ------------------------------------------------------------------ */1150+/* decFloatShow -- printf a decFloat in hexadecimal and decimal */1151+/* df is the decFloat to show */1152+/* tag is a tag string displayed with the number */1153+/* */1154+/* This is a debug aid; the precise format of the string may change. */1155+/* ------------------------------------------------------------------ */1156+void decFloatShow(const decFloat *df, const char *tag) {1157+ char hexbuf[DECBYTES*2+DECBYTES/4+1]; // NB blank after every fourth1158+ char buff[DECSTRING]; // for value in decimal1159+ Int i, j=0;1160+1161+ for (i=0; i<DECBYTES; i++) {1162+ #if DECLITEND1163+ sprintf(&hexbuf[j], "%02x", df->bytes[DECBYTES-1-i]);1164+ #else1165+ sprintf(&hexbuf[j], "%02x", df->bytes[i]);1166+ #endif1167+ j+=2;1168+ // the next line adds blank (and terminator) after final pair, too1169+ if ((i+1)%4==0) {strcpy(&hexbuf[j], " "); j++;}1170+ }1171+ decFloatToString(df, buff);1172+ printf(">%s> %s [big-endian] %s\n", tag, hexbuf, buff);1173+ return;1174+ } // decFloatShow1175+#endif1176+1177+/* ------------------------------------------------------------------ */1178+/* decFloatToBCD -- get sign, exponent, and BCD8 from a decFloat */1179+/* */1180+/* df is the source decFloat */1181+/* exp will be set to the unbiased exponent, q, or to a special */1182+/* value in the form returned by decFloatGetExponent */1183+/* bcdar is where DECPMAX bytes will be written, one BCD digit in */1184+/* each byte (BCD8 encoding); if df is a NaN the first byte will */1185+/* be zero, and if it is infinite they will all be zero */1186+/* returns the sign of the coefficient (DECFLOAT_Sign if negative, */1187+/* 0 otherwise) */1188+/* */1189+/* No error is possible, and no status will be set. */1190+/* ------------------------------------------------------------------ */1191+Int decFloatToBCD(const decFloat *df, Int *exp, uByte *bcdar) {1192+ if (DFISINF(df)) {1193+ memset(bcdar, 0, DECPMAX);1194+ *exp=DFWORD(df, 0)&0x7e000000;1195+ }1196+ else {1197+ GETCOEFF(df, bcdar); // use macro1198+ if (DFISNAN(df)) {1199+ bcdar[0]=0; // MSD needs correcting1200+ *exp=DFWORD(df, 0)&0x7e000000;1201+ }1202+ else { // finite1203+ *exp=GETEXPUN(df);1204+ }1205+ }1206+ return GETSIGN(df);1207+ } // decFloatToBCD1208+1209+/* ------------------------------------------------------------------ */1210+/* decFloatToEngString -- conversion to numeric string, engineering */1211+/* */1212+/* df is the decFloat format number to convert */1213+/* string is the string where the result will be laid out */1214+/* */1215+/* string must be at least DECPMAX+9 characters (the worst case is */1216+/* "-0.00000nnn...nnn\0", which is as long as the exponent form when */1217+/* DECEMAXD<=4); this condition is asserted above */1218+/* */1219+/* No error is possible, and no status will be set */1220+/* ------------------------------------------------------------------ */1221+char * decFloatToEngString(const decFloat *df, char *string){1222+ uInt msd; // coefficient MSD1223+ Int exp; // exponent top two bits or full1224+ uInt comb; // combination field1225+ char *cstart; // coefficient start1226+ char *c; // output pointer in string1227+ char *s, *t; // .. (source, target)1228+ Int pre, e; // work1229+ const uByte *u; // ..1230+ uInt uiwork; // for macros [one compiler needs1231+ // volatile here to avoid bug, but1232+ // that doubles execution time]1233+1234+ // Source words; macro handles endianness1235+ uInt sourhi=DFWORD(df, 0); // word with sign1236+ #if DECPMAX==161237+ uInt sourlo=DFWORD(df, 1);1238+ #elif DECPMAX==341239+ uInt sourmh=DFWORD(df, 1);1240+ uInt sourml=DFWORD(df, 2);1241+ uInt sourlo=DFWORD(df, 3);1242+ #endif1243+1244+ c=string; // where result will go1245+ if (((Int)sourhi)<0) *c++='-'; // handle sign1246+ comb=sourhi>>26; // sign+combination field1247+ msd=DECCOMBMSD[comb]; // decode the combination field1248+ exp=DECCOMBEXP[comb]; // ..1249+1250+ if (EXPISSPECIAL(exp)) { // special1251+ if (exp==DECFLOAT_Inf) { // infinity1252+ strcpy(c, "Inf");1253+ strcpy(c+3, "inity");1254+ return string; // easy1255+ }1256+ if (sourhi&0x02000000) *c++='s'; // sNaN1257+ strcpy(c, "NaN"); // complete word1258+ c+=3; // step past1259+ // quick exit if the payload is zero1260+ #if DECPMAX==71261+ if ((sourhi&0x000fffff)==0) return string;1262+ #elif DECPMAX==161263+ if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;1264+ #elif DECPMAX==341265+ if (sourlo==0 && sourml==0 && sourmh==01266+ && (sourhi&0x00003fff)==0) return string;1267+ #endif1268+ // otherwise drop through to add integer; set correct exp etc.1269+ exp=0; msd=0; // setup for following code1270+ }1271+ else { // complete exponent; top two bits are in place1272+ exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias1273+ }1274+1275+ /* convert the digits of the significand to characters */1276+ cstart=c; // save start of coefficient1277+ if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit1278+1279+ // Decode the declets. After extracting each declet, it is1280+ // decoded to a 4-uByte sequence by table lookup; the four uBytes1281+ // are the three encoded BCD8 digits followed by a 1-byte length1282+ // (significant digits, except that 000 has length 0). This allows1283+ // us to left-align the first declet with non-zero content, then1284+ // the remaining ones are full 3-char length. Fixed-length copies1285+ // are used because variable-length memcpy causes a subroutine call1286+ // in at least two compilers. (The copies are length 4 for speed1287+ // and are safe because the last item in the array is of length1288+ // three and has the length byte following.)1289+ #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \1290+ if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \1291+ else if (*(u+3)) { \1292+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}1293+1294+ #if DECPMAX==71295+ dpd2char(sourhi>>10); // declet 11296+ dpd2char(sourhi); // declet 21297+1298+ #elif DECPMAX==161299+ dpd2char(sourhi>>8); // declet 11300+ dpd2char((sourhi<<2) | (sourlo>>30)); // declet 21301+ dpd2char(sourlo>>20); // declet 31302+ dpd2char(sourlo>>10); // declet 41303+ dpd2char(sourlo); // declet 51304+1305+ #elif DECPMAX==341306+ dpd2char(sourhi>>4); // declet 11307+ dpd2char((sourhi<<6) | (sourmh>>26)); // declet 21308+ dpd2char(sourmh>>16); // declet 31309+ dpd2char(sourmh>>6); // declet 41310+ dpd2char((sourmh<<4) | (sourml>>28)); // declet 51311+ dpd2char(sourml>>18); // declet 61312+ dpd2char(sourml>>8); // declet 71313+ dpd2char((sourml<<2) | (sourlo>>30)); // declet 81314+ dpd2char(sourlo>>20); // declet 91315+ dpd2char(sourlo>>10); // declet 101316+ dpd2char(sourlo); // declet 111317+ #endif1318+1319+ if (c==cstart) *c++='0'; // all zeros, empty -- make "0"1320+1321+ if (exp==0) { // integer or NaN case -- easy1322+ *c='\0'; // terminate1323+ return string;1324+ }1325+ /* non-0 exponent */1326+1327+ e=0; // assume no E1328+ pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]1329+ // [here, pre-exp is the digits count (==1 for zero)]1330+1331+ if (exp>0 || pre<-5) { // need exponential form1332+ e=pre-1; // calculate E value1333+ pre=1; // assume one digit before '.'1334+ if (e!=0) { // engineering: may need to adjust1335+ Int adj; // adjustment1336+ // The C remainder operator is undefined for negative numbers, so1337+ // a positive remainder calculation must be used here1338+ if (e<0) {1339+ adj=(-e)%3;1340+ if (adj!=0) adj=3-adj;1341+ }1342+ else { // e>01343+ adj=e%3;1344+ }1345+ e=e-adj;1346+ // if dealing with zero still produce an exponent which is a1347+ // multiple of three, as expected, but there will only be the1348+ // one zero before the E, still. Otherwise note the padding.1349+ if (!DFISZERO(df)) pre+=adj;1350+ else { // is zero1351+ if (adj!=0) { // 0.00Esnn needed1352+ e=e+3;1353+ pre=-(2-adj);1354+ }1355+ } // zero1356+ } // engineering adjustment1357+ } // exponential form1358+ // printf("e=%ld pre=%ld exp=%ld\n", (LI)e, (LI)pre, (LI)exp);1359+1360+ /* modify the coefficient, adding 0s, '.', and E+nn as needed */1361+ if (pre>0) { // ddd.ddd (plain), perhaps with E1362+ // or dd00 padding for engineering1363+ char *dotat=cstart+pre;1364+ if (dotat<c) { // if embedded dot needed...1365+ // move by fours; there must be space for junk at the end1366+ // because there is still space for exponent1367+ s=dotat+ROUNDDOWN4(c-dotat); // source1368+ t=s+1; // target1369+ // open the gap [cannot use memcpy]1370+ for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));1371+ *dotat='.';1372+ c++; // length increased by one1373+ } // need dot?1374+ else for (; c<dotat; c++) *c='0'; // pad for engineering1375+ } // pre>01376+ else {1377+ /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (may have1378+ E, but only for 0.00E+3 kind of case -- with plenty of spare1379+ space in this case */1380+ pre=-pre+2; // gap width, including "0."1381+ t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point1382+ // backoff if too far to the right1383+ if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit1384+ // now shift the entire coefficient to the right, being careful not1385+ // to access to the left of string [cannot use memcpy]1386+ for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));1387+ // for Quads and Singles there may be a character or two left...1388+ s+=3; // where next would come from1389+ for(; s>=cstart; s--, t--) *(t+3)=*(s);1390+ // now have fill 0. through 0.00000; use overlaps to avoid tests1391+ if (pre>=4) {1392+ memcpy(cstart+pre-4, "0000", 4);1393+ memcpy(cstart, "0.00", 4);1394+ }1395+ else { // 2 or 31396+ *(cstart+pre-1)='0';1397+ memcpy(cstart, "0.", 2);1398+ }1399+ c+=pre; // to end1400+ }1401+1402+ // finally add the E-part, if needed; it will never be 0, and has1403+ // a maximum length of 3 or 4 digits (asserted above)1404+ if (e!=0) {1405+ memcpy(c, "E+", 2); // starts with E, assume +1406+ c++;1407+ if (e<0) {1408+ *c='-'; // oops, need '-'1409+ e=-e; // uInt, please1410+ }1411+ c++;1412+ // Three-character exponents are easy; 4-character a little trickier1413+ #if DECEMAXD<=31414+ u=&BIN2BCD8[e*4]; // -> 3 digits + length byte1415+ // copy fixed 4 characters [is safe], starting at non-zero1416+ // and with character mask to convert BCD to char1417+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);1418+ c+=*(u+3); // bump pointer appropriately1419+ #elif DECEMAXD==41420+ if (e<1000) { // 3 (or fewer) digits case1421+ u=&BIN2BCD8[e*4]; // -> 3 digits + length byte1422+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]1423+ c+=*(u+3); // bump pointer appropriately1424+ }1425+ else { // 4-digits1426+ Int thou=((e>>3)*1049)>>17; // e/10001427+ Int rem=e-(1000*thou); // e%10001428+ *c++=(char)('0'+(char)thou); // the thousands digit1429+ u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte1430+ UBFROMUI(c, UBTOUI(u)|CHARMASK);// copy fixed 3+1 characters [is safe]1431+ c+=3; // bump pointer, always 3 digits1432+ }1433+ #endif1434+ }1435+ *c='\0'; // terminate1436+ //printf("res %s\n", string);1437+ return string;1438+ } // decFloatToEngString1439+1440+/* ------------------------------------------------------------------ */1441+/* decFloatToPacked -- convert decFloat to Packed decimal + exponent */1442+/* */1443+/* df is the source decFloat */1444+/* exp will be set to the unbiased exponent, q, or to a special */1445+/* value in the form returned by decFloatGetExponent */1446+/* packed is where DECPMAX nibbles will be written with the sign as */1447+/* final nibble (0x0c for +, 0x0d for -); a NaN has a first nibble */1448+/* of zero, and an infinity is all zeros. decDouble and decQuad */1449+/* have a additional leading zero nibble, leading to result */1450+/* lengths of 4, 9, and 18 bytes. */1451+/* returns the sign of the coefficient (DECFLOAT_Sign if negative, */1452+/* 0 otherwise) */1453+/* */1454+/* No error is possible, and no status will be set. */1455+/* ------------------------------------------------------------------ */1456+Int decFloatToPacked(const decFloat *df, Int *exp, uByte *packed) {1457+ uByte bcdar[DECPMAX+2]; // work buffer1458+ uByte *ip=bcdar, *op=packed; // work pointers1459+ if (DFISINF(df)) {1460+ memset(bcdar, 0, DECPMAX+2);1461+ *exp=DECFLOAT_Inf;1462+ }1463+ else {1464+ GETCOEFF(df, bcdar+1); // use macro1465+ if (DFISNAN(df)) {1466+ bcdar[1]=0; // MSD needs clearing1467+ *exp=DFWORD(df, 0)&0x7e000000;1468+ }1469+ else { // finite1470+ *exp=GETEXPUN(df);1471+ }1472+ }1473+ // now pack; coefficient currently at bcdar+11474+ #if SINGLE1475+ ip++; // ignore first byte1476+ #else1477+ *ip=0; // need leading zero1478+ #endif1479+ // set final byte to Packed BCD sign value1480+ bcdar[DECPMAX+1]=(DFISSIGNED(df) ? DECPMINUS : DECPPLUS);1481+ // pack an even number of bytes...1482+ for (; op<packed+((DECPMAX+2)/2); op++, ip+=2) {1483+ *op=(uByte)((*ip<<4)+*(ip+1));1484+ }1485+ return (bcdar[DECPMAX+1]==DECPMINUS ? DECFLOAT_Sign : 0);1486+ } // decFloatToPacked1487+1488+/* ------------------------------------------------------------------ */1489+/* decFloatToString -- conversion to numeric string */1490+/* */1491+/* df is the decFloat format number to convert */1492+/* string is the string where the result will be laid out */1493+/* */1494+/* string must be at least DECPMAX+9 characters (the worst case is */1495+/* "-0.00000nnn...nnn\0", which is as long as the exponent form when */1496+/* DECEMAXD<=4); this condition is asserted above */1497+/* */1498+/* No error is possible, and no status will be set */1499+/* ------------------------------------------------------------------ */1500+char * decFloatToString(const decFloat *df, char *string){1501+ uInt msd; // coefficient MSD1502+ Int exp; // exponent top two bits or full1503+ uInt comb; // combination field1504+ char *cstart; // coefficient start1505+ char *c; // output pointer in string1506+ char *s, *t; // .. (source, target)1507+ Int pre, e; // work1508+ const uByte *u; // ..1509+ uInt uiwork; // for macros [one compiler needs1510+ // volatile here to avoid bug, but1511+ // that doubles execution time]1512+1513+ // Source words; macro handles endianness1514+ uInt sourhi=DFWORD(df, 0); // word with sign1515+ #if DECPMAX==161516+ uInt sourlo=DFWORD(df, 1);1517+ #elif DECPMAX==341518+ uInt sourmh=DFWORD(df, 1);1519+ uInt sourml=DFWORD(df, 2);1520+ uInt sourlo=DFWORD(df, 3);1521+ #endif1522+1523+ c=string; // where result will go1524+ if (((Int)sourhi)<0) *c++='-'; // handle sign1525+ comb=sourhi>>26; // sign+combination field1526+ msd=DECCOMBMSD[comb]; // decode the combination field1527+ exp=DECCOMBEXP[comb]; // ..1528+1529+ if (!EXPISSPECIAL(exp)) { // finite1530+ // complete exponent; top two bits are in place1531+ exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias1532+ }1533+ else { // IS special1534+ if (exp==DECFLOAT_Inf) { // infinity1535+ strcpy(c, "Infinity");1536+ return string; // easy1537+ }1538+ if (sourhi&0x02000000) *c++='s'; // sNaN1539+ strcpy(c, "NaN"); // complete word1540+ c+=3; // step past1541+ // quick exit if the payload is zero1542+ #if DECPMAX==71543+ if ((sourhi&0x000fffff)==0) return string;1544+ #elif DECPMAX==161545+ if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;1546+ #elif DECPMAX==341547+ if (sourlo==0 && sourml==0 && sourmh==01548+ && (sourhi&0x00003fff)==0) return string;1549+ #endif1550+ // otherwise drop through to add integer; set correct exp etc.1551+ exp=0; msd=0; // setup for following code1552+ }1553+1554+ /* convert the digits of the significand to characters */1555+ cstart=c; // save start of coefficient1556+ if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit1557+1558+ // Decode the declets. After extracting each declet, it is1559+ // decoded to a 4-uByte sequence by table lookup; the four uBytes1560+ // are the three encoded BCD8 digits followed by a 1-byte length1561+ // (significant digits, except that 000 has length 0). This allows1562+ // us to left-align the first declet with non-zero content, then1563+ // the remaining ones are full 3-char length. Fixed-length copies1564+ // are used because variable-length memcpy causes a subroutine call1565+ // in at least two compilers. (The copies are length 4 for speed1566+ // and are safe because the last item in the array is of length1567+ // three and has the length byte following.)1568+ #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \1569+ if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \1570+ else if (*(u+3)) { \1571+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}1572+1573+ #if DECPMAX==71574+ dpd2char(sourhi>>10); // declet 11575+ dpd2char(sourhi); // declet 21576+1577+ #elif DECPMAX==161578+ dpd2char(sourhi>>8); // declet 11579+ dpd2char((sourhi<<2) | (sourlo>>30)); // declet 21580+ dpd2char(sourlo>>20); // declet 31581+ dpd2char(sourlo>>10); // declet 41582+ dpd2char(sourlo); // declet 51583+1584+ #elif DECPMAX==341585+ dpd2char(sourhi>>4); // declet 11586+ dpd2char((sourhi<<6) | (sourmh>>26)); // declet 21587+ dpd2char(sourmh>>16); // declet 31588+ dpd2char(sourmh>>6); // declet 41589+ dpd2char((sourmh<<4) | (sourml>>28)); // declet 51590+ dpd2char(sourml>>18); // declet 61591+ dpd2char(sourml>>8); // declet 71592+ dpd2char((sourml<<2) | (sourlo>>30)); // declet 81593+ dpd2char(sourlo>>20); // declet 91594+ dpd2char(sourlo>>10); // declet 101595+ dpd2char(sourlo); // declet 111596+ #endif1597+1598+ if (c==cstart) *c++='0'; // all zeros, empty -- make "0"1599+1600+ //[This fast path is valid but adds 3-5 cycles to worst case length]1601+ //if (exp==0) { // integer or NaN case -- easy1602+ // *c='\0'; // terminate1603+ // return string;1604+ // }1605+1606+ e=0; // assume no E1607+ pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]1608+ // [here, pre-exp is the digits count (==1 for zero)]1609+1610+ if (exp>0 || pre<-5) { // need exponential form1611+ e=pre-1; // calculate E value1612+ pre=1; // assume one digit before '.'1613+ } // exponential form1614+1615+ /* modify the coefficient, adding 0s, '.', and E+nn as needed */1616+ if (pre>0) { // ddd.ddd (plain), perhaps with E1617+ char *dotat=cstart+pre;1618+ if (dotat<c) { // if embedded dot needed...1619+ // [memmove is a disaster, here]1620+ // move by fours; there must be space for junk at the end1621+ // because exponent is still possible1622+ s=dotat+ROUNDDOWN4(c-dotat); // source1623+ t=s+1; // target1624+ // open the gap [cannot use memcpy]1625+ for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));1626+ *dotat='.';1627+ c++; // length increased by one1628+ } // need dot?1629+1630+ // finally add the E-part, if needed; it will never be 0, and has1631+ // a maximum length of 3 or 4 digits (asserted above)1632+ if (e!=0) {1633+ memcpy(c, "E+", 2); // starts with E, assume +1634+ c++;1635+ if (e<0) {1636+ *c='-'; // oops, need '-'1637+ e=-e; // uInt, please1638+ }1639+ c++;1640+ // Three-character exponents are easy; 4-character a little trickier1641+ #if DECEMAXD<=31642+ u=&BIN2BCD8[e*4]; // -> 3 digits + length byte1643+ // copy fixed 4 characters [is safe], starting at non-zero1644+ // and with character mask to convert BCD to char1645+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);1646+ c+=*(u+3); // bump pointer appropriately1647+ #elif DECEMAXD==41648+ if (e<1000) { // 3 (or fewer) digits case1649+ u=&BIN2BCD8[e*4]; // -> 3 digits + length byte1650+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]1651+ c+=*(u+3); // bump pointer appropriately1652+ }1653+ else { // 4-digits1654+ Int thou=((e>>3)*1049)>>17; // e/10001655+ Int rem=e-(1000*thou); // e%10001656+ *c++=(char)('0'+(char)thou); // the thousands digit1657+ u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte1658+ UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]1659+ c+=3; // bump pointer, always 3 digits1660+ }1661+ #endif1662+ }1663+ *c='\0'; // add terminator1664+ //printf("res %s\n", string);1665+ return string;1666+ } // pre>01667+1668+ /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */1669+ // Surprisingly, this is close to being the worst-case path, so the1670+ // shift is done by fours; this is a little tricky because the1671+ // rightmost character to be written must not be beyond where the1672+ // rightmost terminator could be -- so backoff to not touch1673+ // terminator position if need be (this can make exact alignments1674+ // for full Doubles, but in some cases needs care not to access too1675+ // far to the left)1676+1677+ pre=-pre+2; // gap width, including "0."1678+ t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point1679+ // backoff if too far to the right1680+ if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit1681+ // now shift the entire coefficient to the right, being careful not1682+ // to access to the left of string [cannot use memcpy]1683+ for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));1684+ // for Quads and Singles there may be a character or two left...1685+ s+=3; // where next would come from1686+ for(; s>=cstart; s--, t--) *(t+3)=*(s);1687+ // now have fill 0. through 0.00000; use overlaps to avoid tests1688+ if (pre>=4) {1689+ memcpy(cstart+pre-4, "0000", 4);1690+ memcpy(cstart, "0.00", 4);1691+ }1692+ else { // 2 or 31693+ *(cstart+pre-1)='0';1694+ memcpy(cstart, "0.", 2);1695+ }1696+ *(c+pre)='\0'; // terminate1697+ return string;1698+ } // decFloatToString1699+1700+/* ------------------------------------------------------------------ */1701+/* decFloatToWider -- conversion to next-wider format */1702+/* */1703+/* source is the decFloat format number which gets the result of */1704+/* the conversion */1705+/* wider is the decFloatWider format number which will be narrowed */1706+/* returns wider */1707+/* */1708+/* Widening is always exact; no status is set (sNaNs are copied and */1709+/* do not signal). The result will be canonical if the source is, */1710+/* and may or may not be if the source is not. */1711+/* ------------------------------------------------------------------ */1712+// widening is not possible for decQuad format numbers; simply omit1713+#if !QUAD1714+decFloatWider * decFloatToWider(const decFloat *source, decFloatWider *wider) {1715+ uInt msd;1716+1717+ /* Construct and copy the sign word */1718+ if (DFISSPECIAL(source)) {1719+ // copy sign, combination, and first bit of exponent (sNaN selector)1720+ DFWWORD(wider, 0)=DFWORD(source, 0)&0xfe000000;1721+ msd=0;1722+ }1723+ else { // is finite number1724+ uInt exp=GETEXPUN(source)+DECWBIAS; // get unbiased exponent and rebias1725+ uInt code=(exp>>DECWECONL)<<29; // set two bits of exp [msd=0]1726+ code|=(exp<<(32-6-DECWECONL)) & 0x03ffffff; // add exponent continuation1727+ code|=DFWORD(source, 0)&0x80000000; // add sign1728+ DFWWORD(wider, 0)=code; // .. and place top word in wider1729+ msd=GETMSD(source); // get source coefficient MSD [0-9]1730+ }1731+ /* Copy the coefficient and clear any 'unused' words to left */1732+ #if SINGLE1733+ DFWWORD(wider, 1)=(DFWORD(source, 0)&0x000fffff)|(msd<<20);1734+ #elif DOUBLE1735+ DFWWORD(wider, 2)=(DFWORD(source, 0)&0x0003ffff)|(msd<<18);1736+ DFWWORD(wider, 3)=DFWORD(source, 1);1737+ DFWWORD(wider, 1)=0;1738+ #endif1739+ return wider;1740+ } // decFloatToWider1741+#endif1742+1743+/* ------------------------------------------------------------------ */1744+/* decFloatVersion -- return package version string */1745+/* */1746+/* returns a constant string describing this package */1747+/* ------------------------------------------------------------------ */1748+const char *decFloatVersion(void) {1749+ return DECVERSION;1750+ } // decFloatVersion1751+1752+/* ------------------------------------------------------------------ */1753+/* decFloatZero -- set to canonical (integer) zero */1754+/* */1755+/* df is the decFloat format number to integer +0 (q=0, c=+0) */1756+/* returns df */1757+/* */1758+/* No error is possible, and no status can be set. */1759+/* ------------------------------------------------------------------ */1760+decFloat * decFloatZero(decFloat *df){1761+ DFWORD(df, 0)=ZEROWORD; // set appropriate top word1762+ #if DOUBLE || QUAD1763+ DFWORD(df, 1)=0;1764+ #if QUAD1765+ DFWORD(df, 2)=0;1766+ DFWORD(df, 3)=0;1767+ #endif1768+ #endif1769+ // decFloatShow(df, "zero");1770+ return df;1771+ } // decFloatZero1772+1773+/* ------------------------------------------------------------------ */1774+/* Private generic function (not format-specific) for development use */1775+/* ------------------------------------------------------------------ */1776+// This is included once only, for all to use1777+#if QUAD && (DECCHECK || DECTRACE)1778+ /* ---------------------------------------------------------------- */1779+ /* decShowNum -- display bcd8 number in debug form */1780+ /* */1781+ /* num is the bcdnum to display */1782+ /* tag is a string to label the display */1783+ /* ---------------------------------------------------------------- */1784+ void decShowNum(const bcdnum *num, const char *tag) {1785+ const char *csign="+"; // sign character1786+ uByte *ub; // work1787+ uInt uiwork; // for macros1788+ if (num->sign==DECFLOAT_Sign) csign="-";1789+1790+ printf(">%s> ", tag);1791+ if (num->exponent==DECFLOAT_Inf) printf("%sInfinity", csign);1792+ else if (num->exponent==DECFLOAT_qNaN) printf("%sqNaN", csign);1793+ else if (num->exponent==DECFLOAT_sNaN) printf("%ssNaN", csign);1794+ else { // finite1795+ char qbuf[10]; // for right-aligned q1796+ char *c; // work1797+ const uByte *u; // ..1798+ Int e=num->exponent; // .. exponent1799+ strcpy(qbuf, "q=");1800+ c=&qbuf[2]; // where exponent will go1801+ // lay out the exponent1802+ if (e<0) {1803+ *c++='-'; // add '-'1804+ e=-e; // uInt, please1805+ }1806+ #if DECEMAXD>41807+ #error Exponent form is too long for ShowNum to lay out1808+ #endif1809+ if (e==0) *c++='0'; // 0-length case1810+ else if (e<1000) { // 3 (or fewer) digits case1811+ u=&BIN2BCD8[e*4]; // -> 3 digits + length byte1812+ UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]1813+ c+=*(u+3); // bump pointer appropriately1814+ }1815+ else { // 4-digits1816+ Int thou=((e>>3)*1049)>>17; // e/10001817+ Int rem=e-(1000*thou); // e%10001818+ *c++=(char)('0'+(char)thou); // the thousands digit1819+ u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte1820+ UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]1821+ c+=3; // bump pointer, always 3 digits1822+ }1823+ *c='\0'; // add terminator1824+ printf("%7s c=%s", qbuf, csign);1825+ }1826+1827+ if (!EXPISSPECIAL(num->exponent) || num->msd!=num->lsd || *num->lsd!=0) {1828+ for (ub=num->msd; ub<=num->lsd; ub++) { // coefficient...1829+ printf("%1x", *ub);1830+ if ((num->lsd-ub)%3==0 && ub!=num->lsd) printf(" "); // 4-space1831+ }1832+ }1833+ printf("\n");1834+ } // decShowNum1835+#endifadded:src/decNumber/decContext.c+437 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Context module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2009. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for handling arithmetic */20+/* context structures. */21+/* ------------------------------------------------------------------ */22+23+#include <string.h> // for strcmp24+#include <stdio.h> // for printf if DECCHECK25+#include "decContext.h" // context and base types26+#include "decNumberLocal.h" // decNumber local types, etc.27+28+/* compile-time endian tester [assumes sizeof(Int)>1] */29+static const Int mfcone=1; // constant 130+static const Flag *mfctop=(const Flag *)&mfcone; // -> top byte31+#define LITEND *mfctop // named flag; 1=little-endian32+33+/* ------------------------------------------------------------------ */34+/* round-for-reround digits */35+/* ------------------------------------------------------------------ */36+const uByte DECSTICKYTAB[10]={1,1,2,3,4,6,6,7,8,9}; /* used if sticky */37+38+/* ------------------------------------------------------------------ */39+/* Powers of ten (powers[n]==10**n, 0<=n<=9) */40+/* ------------------------------------------------------------------ */41+const uInt DECPOWERS[10]={1, 10, 100, 1000, 10000, 100000, 1000000,42+ 10000000, 100000000, 1000000000};43+44+/* ------------------------------------------------------------------ */45+/* decContextClearStatus -- clear bits in current status */46+/* */47+/* context is the context structure to be queried */48+/* mask indicates the bits to be cleared (the status bit that */49+/* corresponds to each 1 bit in the mask is cleared) */50+/* returns context */51+/* */52+/* No error is possible. */53+/* ------------------------------------------------------------------ */54+decContext *decContextClearStatus(decContext *context, uInt mask) {55+ context->status&=~mask;56+ return context;57+ } // decContextClearStatus58+59+/* ------------------------------------------------------------------ */60+/* decContextDefault -- initialize a context structure */61+/* */62+/* context is the structure to be initialized */63+/* kind selects the required set of default values, one of: */64+/* DEC_INIT_BASE -- select ANSI X3-274 defaults */65+/* DEC_INIT_DECIMAL32 -- select IEEE 754 defaults, 32-bit */66+/* DEC_INIT_DECIMAL64 -- select IEEE 754 defaults, 64-bit */67+/* DEC_INIT_DECIMAL128 -- select IEEE 754 defaults, 128-bit */68+/* For any other value a valid context is returned, but with */69+/* Invalid_operation set in the status field. */70+/* returns a context structure with the appropriate initial values. */71+/* ------------------------------------------------------------------ */72+decContext * decContextDefault(decContext *context, Int kind) {73+ // set defaults...74+ context->digits=9; // 9 digits75+ context->emax=DEC_MAX_EMAX; // 9-digit exponents76+ context->emin=DEC_MIN_EMIN; // .. balanced77+ context->round=DEC_ROUND_HALF_UP; // 0.5 rises78+ context->traps=DEC_Errors; // all but informational79+ context->status=0; // cleared80+ context->clamp=0; // no clamping81+ #if DECSUBSET82+ context->extended=0; // cleared83+ #endif84+ switch (kind) {85+ case DEC_INIT_BASE:86+ // [use defaults]87+ break;88+ case DEC_INIT_DECIMAL32:89+ context->digits=7; // digits90+ context->emax=96; // Emax91+ context->emin=-95; // Emin92+ context->round=DEC_ROUND_HALF_EVEN; // 0.5 to nearest even93+ context->traps=0; // no traps set94+ context->clamp=1; // clamp exponents95+ #if DECSUBSET96+ context->extended=1; // set97+ #endif98+ break;99+ case DEC_INIT_DECIMAL64:100+ context->digits=16; // digits101+ context->emax=384; // Emax102+ context->emin=-383; // Emin103+ context->round=DEC_ROUND_HALF_EVEN; // 0.5 to nearest even104+ context->traps=0; // no traps set105+ context->clamp=1; // clamp exponents106+ #if DECSUBSET107+ context->extended=1; // set108+ #endif109+ break;110+ case DEC_INIT_DECIMAL128:111+ context->digits=34; // digits112+ context->emax=6144; // Emax113+ context->emin=-6143; // Emin114+ context->round=DEC_ROUND_HALF_EVEN; // 0.5 to nearest even115+ context->traps=0; // no traps set116+ context->clamp=1; // clamp exponents117+ #if DECSUBSET118+ context->extended=1; // set119+ #endif120+ break;121+122+ default: // invalid Kind123+ // use defaults, and ..124+ decContextSetStatus(context, DEC_Invalid_operation); // trap125+ }126+127+ return context;} // decContextDefault128+129+/* ------------------------------------------------------------------ */130+/* decContextGetRounding -- return current rounding mode */131+/* */132+/* context is the context structure to be queried */133+/* returns the rounding mode */134+/* */135+/* No error is possible. */136+/* ------------------------------------------------------------------ */137+enum rounding decContextGetRounding(decContext *context) {138+ return context->round;139+ } // decContextGetRounding140+141+/* ------------------------------------------------------------------ */142+/* decContextGetStatus -- return current status */143+/* */144+/* context is the context structure to be queried */145+/* returns status */146+/* */147+/* No error is possible. */148+/* ------------------------------------------------------------------ */149+uInt decContextGetStatus(decContext *context) {150+ return context->status;151+ } // decContextGetStatus152+153+/* ------------------------------------------------------------------ */154+/* decContextRestoreStatus -- restore bits in current status */155+/* */156+/* context is the context structure to be updated */157+/* newstatus is the source for the bits to be restored */158+/* mask indicates the bits to be restored (the status bit that */159+/* corresponds to each 1 bit in the mask is set to the value of */160+/* the correspnding bit in newstatus) */161+/* returns context */162+/* */163+/* No error is possible. */164+/* ------------------------------------------------------------------ */165+decContext *decContextRestoreStatus(decContext *context,166+ uInt newstatus, uInt mask) {167+ context->status&=~mask; // clear the selected bits168+ context->status|=(mask&newstatus); // or in the new bits169+ return context;170+ } // decContextRestoreStatus171+172+/* ------------------------------------------------------------------ */173+/* decContextSaveStatus -- save bits in current status */174+/* */175+/* context is the context structure to be queried */176+/* mask indicates the bits to be saved (the status bits that */177+/* correspond to each 1 bit in the mask are saved) */178+/* returns the AND of the mask and the current status */179+/* */180+/* No error is possible. */181+/* ------------------------------------------------------------------ */182+uInt decContextSaveStatus(decContext *context, uInt mask) {183+ return context->status&mask;184+ } // decContextSaveStatus185+186+/* ------------------------------------------------------------------ */187+/* decContextSetRounding -- set current rounding mode */188+/* */189+/* context is the context structure to be updated */190+/* newround is the value which will replace the current mode */191+/* returns context */192+/* */193+/* No error is possible. */194+/* ------------------------------------------------------------------ */195+decContext *decContextSetRounding(decContext *context,196+ enum rounding newround) {197+ context->round=newround;198+ return context;199+ } // decContextSetRounding200+201+/* ------------------------------------------------------------------ */202+/* decContextSetStatus -- set status and raise trap if appropriate */203+/* */204+/* context is the context structure to be updated */205+/* status is the DEC_ exception code */206+/* returns the context structure */207+/* */208+/* Control may never return from this routine, if there is a signal */209+/* handler and it takes a long jump. */210+/* ------------------------------------------------------------------ */211+decContext * decContextSetStatus(decContext *context, uInt status) {212+ context->status|=status;213+ if (status & context->traps) raise(SIGFPE);214+ return context;} // decContextSetStatus215+216+/* ------------------------------------------------------------------ */217+/* decContextSetStatusFromString -- set status from a string + trap */218+/* */219+/* context is the context structure to be updated */220+/* string is a string exactly equal to one that might be returned */221+/* by decContextStatusToString */222+/* */223+/* The status bit corresponding to the string is set, and a trap */224+/* is raised if appropriate. */225+/* */226+/* returns the context structure, unless the string is equal to */227+/* DEC_Condition_MU or is not recognized. In these cases NULL is */228+/* returned. */229+/* ------------------------------------------------------------------ */230+decContext * decContextSetStatusFromString(decContext *context,231+ const char *string) {232+ if (strcmp(string, DEC_Condition_CS)==0)233+ return decContextSetStatus(context, DEC_Conversion_syntax);234+ if (strcmp(string, DEC_Condition_DZ)==0)235+ return decContextSetStatus(context, DEC_Division_by_zero);236+ if (strcmp(string, DEC_Condition_DI)==0)237+ return decContextSetStatus(context, DEC_Division_impossible);238+ if (strcmp(string, DEC_Condition_DU)==0)239+ return decContextSetStatus(context, DEC_Division_undefined);240+ if (strcmp(string, DEC_Condition_IE)==0)241+ return decContextSetStatus(context, DEC_Inexact);242+ if (strcmp(string, DEC_Condition_IS)==0)243+ return decContextSetStatus(context, DEC_Insufficient_storage);244+ if (strcmp(string, DEC_Condition_IC)==0)245+ return decContextSetStatus(context, DEC_Invalid_context);246+ if (strcmp(string, DEC_Condition_IO)==0)247+ return decContextSetStatus(context, DEC_Invalid_operation);248+ #if DECSUBSET249+ if (strcmp(string, DEC_Condition_LD)==0)250+ return decContextSetStatus(context, DEC_Lost_digits);251+ #endif252+ if (strcmp(string, DEC_Condition_OV)==0)253+ return decContextSetStatus(context, DEC_Overflow);254+ if (strcmp(string, DEC_Condition_PA)==0)255+ return decContextSetStatus(context, DEC_Clamped);256+ if (strcmp(string, DEC_Condition_RO)==0)257+ return decContextSetStatus(context, DEC_Rounded);258+ if (strcmp(string, DEC_Condition_SU)==0)259+ return decContextSetStatus(context, DEC_Subnormal);260+ if (strcmp(string, DEC_Condition_UN)==0)261+ return decContextSetStatus(context, DEC_Underflow);262+ if (strcmp(string, DEC_Condition_ZE)==0)263+ return context;264+ return NULL; // Multiple status, or unknown265+ } // decContextSetStatusFromString266+267+/* ------------------------------------------------------------------ */268+/* decContextSetStatusFromStringQuiet -- set status from a string */269+/* */270+/* context is the context structure to be updated */271+/* string is a string exactly equal to one that might be returned */272+/* by decContextStatusToString */273+/* */274+/* The status bit corresponding to the string is set; no trap is */275+/* raised. */276+/* */277+/* returns the context structure, unless the string is equal to */278+/* DEC_Condition_MU or is not recognized. In these cases NULL is */279+/* returned. */280+/* ------------------------------------------------------------------ */281+decContext * decContextSetStatusFromStringQuiet(decContext *context,282+ const char *string) {283+ if (strcmp(string, DEC_Condition_CS)==0)284+ return decContextSetStatusQuiet(context, DEC_Conversion_syntax);285+ if (strcmp(string, DEC_Condition_DZ)==0)286+ return decContextSetStatusQuiet(context, DEC_Division_by_zero);287+ if (strcmp(string, DEC_Condition_DI)==0)288+ return decContextSetStatusQuiet(context, DEC_Division_impossible);289+ if (strcmp(string, DEC_Condition_DU)==0)290+ return decContextSetStatusQuiet(context, DEC_Division_undefined);291+ if (strcmp(string, DEC_Condition_IE)==0)292+ return decContextSetStatusQuiet(context, DEC_Inexact);293+ if (strcmp(string, DEC_Condition_IS)==0)294+ return decContextSetStatusQuiet(context, DEC_Insufficient_storage);295+ if (strcmp(string, DEC_Condition_IC)==0)296+ return decContextSetStatusQuiet(context, DEC_Invalid_context);297+ if (strcmp(string, DEC_Condition_IO)==0)298+ return decContextSetStatusQuiet(context, DEC_Invalid_operation);299+ #if DECSUBSET300+ if (strcmp(string, DEC_Condition_LD)==0)301+ return decContextSetStatusQuiet(context, DEC_Lost_digits);302+ #endif303+ if (strcmp(string, DEC_Condition_OV)==0)304+ return decContextSetStatusQuiet(context, DEC_Overflow);305+ if (strcmp(string, DEC_Condition_PA)==0)306+ return decContextSetStatusQuiet(context, DEC_Clamped);307+ if (strcmp(string, DEC_Condition_RO)==0)308+ return decContextSetStatusQuiet(context, DEC_Rounded);309+ if (strcmp(string, DEC_Condition_SU)==0)310+ return decContextSetStatusQuiet(context, DEC_Subnormal);311+ if (strcmp(string, DEC_Condition_UN)==0)312+ return decContextSetStatusQuiet(context, DEC_Underflow);313+ if (strcmp(string, DEC_Condition_ZE)==0)314+ return context;315+ return NULL; // Multiple status, or unknown316+ } // decContextSetStatusFromStringQuiet317+318+/* ------------------------------------------------------------------ */319+/* decContextSetStatusQuiet -- set status without trap */320+/* */321+/* context is the context structure to be updated */322+/* status is the DEC_ exception code */323+/* returns the context structure */324+/* */325+/* No error is possible. */326+/* ------------------------------------------------------------------ */327+decContext * decContextSetStatusQuiet(decContext *context, uInt status) {328+ context->status|=status;329+ return context;} // decContextSetStatusQuiet330+331+/* ------------------------------------------------------------------ */332+/* decContextStatusToString -- convert status flags to a string */333+/* */334+/* context is a context with valid status field */335+/* */336+/* returns a constant string describing the condition. If multiple */337+/* (or no) flags are set, a generic constant message is returned. */338+/* ------------------------------------------------------------------ */339+const char *decContextStatusToString(const decContext *context) {340+ Int status=context->status;341+342+ // test the five IEEE first, as some of the others are ambiguous when343+ // DECEXTFLAG=0344+ if (status==DEC_Invalid_operation ) return DEC_Condition_IO;345+ if (status==DEC_Division_by_zero ) return DEC_Condition_DZ;346+ if (status==DEC_Overflow ) return DEC_Condition_OV;347+ if (status==DEC_Underflow ) return DEC_Condition_UN;348+ if (status==DEC_Inexact ) return DEC_Condition_IE;349+350+ if (status==DEC_Division_impossible ) return DEC_Condition_DI;351+ if (status==DEC_Division_undefined ) return DEC_Condition_DU;352+ if (status==DEC_Rounded ) return DEC_Condition_RO;353+ if (status==DEC_Clamped ) return DEC_Condition_PA;354+ if (status==DEC_Subnormal ) return DEC_Condition_SU;355+ if (status==DEC_Conversion_syntax ) return DEC_Condition_CS;356+ if (status==DEC_Insufficient_storage ) return DEC_Condition_IS;357+ if (status==DEC_Invalid_context ) return DEC_Condition_IC;358+ #if DECSUBSET359+ if (status==DEC_Lost_digits ) return DEC_Condition_LD;360+ #endif361+ if (status==0 ) return DEC_Condition_ZE;362+ return DEC_Condition_MU; // Multiple errors363+ } // decContextStatusToString364+365+/* ------------------------------------------------------------------ */366+/* decContextTestEndian -- test whether DECLITEND is set correctly */367+/* */368+/* quiet is 1 to suppress message; 0 otherwise */369+/* returns 0 if DECLITEND is correct */370+/* 1 if DECLITEND is incorrect and should be 1 */371+/* -1 if DECLITEND is incorrect and should be 0 */372+/* */373+/* A message is displayed if the return value is not 0 and quiet==0. */374+/* */375+/* No error is possible. */376+/* ------------------------------------------------------------------ */377+Int decContextTestEndian(Flag quiet) {378+ Int res=0; // optimist379+ uInt dle=(uInt)DECLITEND; // unsign380+ if (dle>1) dle=1; // ensure 0 or 1381+382+ if (LITEND!=DECLITEND) {383+ if (!quiet) { // always refer to this384+ #if DECPRINT385+ const char *adj;386+ if (LITEND) adj="little";387+ else adj="big";388+ printf("Warning: DECLITEND is set to %d, but this computer appears to be %s-endian\n",389+ DECLITEND, adj);390+ #endif391+ }392+ res=(Int)LITEND-dle;393+ }394+ return res;395+ } // decContextTestEndian396+397+/* ------------------------------------------------------------------ */398+/* decContextTestSavedStatus -- test bits in saved status */399+/* */400+/* oldstatus is the status word to be tested */401+/* mask indicates the bits to be tested (the oldstatus bits that */402+/* correspond to each 1 bit in the mask are tested) */403+/* returns 1 if any of the tested bits are 1, or 0 otherwise */404+/* */405+/* No error is possible. */406+/* ------------------------------------------------------------------ */407+uInt decContextTestSavedStatus(uInt oldstatus, uInt mask) {408+ return (oldstatus&mask)!=0;409+ } // decContextTestSavedStatus410+411+/* ------------------------------------------------------------------ */412+/* decContextTestStatus -- test bits in current status */413+/* */414+/* context is the context structure to be updated */415+/* mask indicates the bits to be tested (the status bits that */416+/* correspond to each 1 bit in the mask are tested) */417+/* returns 1 if any of the tested bits are 1, or 0 otherwise */418+/* */419+/* No error is possible. */420+/* ------------------------------------------------------------------ */421+uInt decContextTestStatus(decContext *context, uInt mask) {422+ return (context->status&mask)!=0;423+ } // decContextTestStatus424+425+/* ------------------------------------------------------------------ */426+/* decContextZeroStatus -- clear all status bits */427+/* */428+/* context is the context structure to be updated */429+/* returns context */430+/* */431+/* No error is possible. */432+/* ------------------------------------------------------------------ */433+decContext *decContextZeroStatus(decContext *context) {434+ context->status=0;435+ return context;436+ } // decContextZeroStatus437+added:src/decNumber/decContext.h+254 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Context module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* */20+/* Context variables must always have valid values: */21+/* */22+/* status -- [any bits may be cleared, but not set, by user] */23+/* round -- must be one of the enumerated rounding modes */24+/* */25+/* The following variables are implied for fixed size formats (i.e., */26+/* they are ignored) but should still be set correctly in case used */27+/* with decNumber functions: */28+/* */29+/* clamp -- must be either 0 or 1 */30+/* digits -- must be in the range 1 through 999999999 */31+/* emax -- must be in the range 0 through 999999999 */32+/* emin -- must be in the range 0 through -999999999 */33+/* extended -- must be either 0 or 1 [present only if DECSUBSET] */34+/* traps -- only defined bits may be set */35+/* */36+/* ------------------------------------------------------------------ */37+38+#if !defined(DECCONTEXT)39+ #define DECCONTEXT40+ #define DECCNAME "decContext" /* Short name */41+ #define DECCFULLNAME "Decimal Context Descriptor" /* Verbose name */42+ #define DECCAUTHOR "Mike Cowlishaw" /* Who to blame */43+44+ #if !defined(int32_t)45+ #include <stdint.h> /* C99 standard integers */46+ #endif47+ #include <stdio.h> /* for printf, etc. */48+ #include <signal.h> /* for traps */49+50+ /* Extended flags setting -- set this to 0 to use only IEEE flags */51+ #if !defined(DECEXTFLAG)52+ #define DECEXTFLAG 1 /* 1=enable extended flags */53+ #endif54+55+ /* Conditional code flag -- set this to 0 for best performance */56+ #if !defined(DECSUBSET)57+ #define DECSUBSET 0 /* 1=enable subset arithmetic */58+ #endif59+60+ /* Context for operations, with associated constants */61+ enum rounding {62+ DEC_ROUND_CEILING, /* round towards +infinity */63+ DEC_ROUND_UP, /* round away from 0 */64+ DEC_ROUND_HALF_UP, /* 0.5 rounds up */65+ DEC_ROUND_HALF_EVEN, /* 0.5 rounds to nearest even */66+ DEC_ROUND_HALF_DOWN, /* 0.5 rounds down */67+ DEC_ROUND_DOWN, /* round towards 0 (truncate) */68+ DEC_ROUND_FLOOR, /* round towards -infinity */69+ DEC_ROUND_05UP, /* round for reround */70+ DEC_ROUND_MAX /* enum must be less than this */71+ };72+ #define DEC_ROUND_DEFAULT DEC_ROUND_HALF_EVEN;73+74+ typedef struct {75+ int32_t digits; /* working precision */76+ int32_t emax; /* maximum positive exponent */77+ int32_t emin; /* minimum negative exponent */78+ enum rounding round; /* rounding mode */79+ uint32_t traps; /* trap-enabler flags */80+ uint32_t status; /* status flags */81+ uint8_t clamp; /* flag: apply IEEE exponent clamp */82+ #if DECSUBSET83+ uint8_t extended; /* flag: special-values allowed */84+ #endif85+ } decContext;86+87+ /* Maxima and Minima for context settings */88+ #define DEC_MAX_DIGITS 99999999989+ #define DEC_MIN_DIGITS 190+ #define DEC_MAX_EMAX 99999999991+ #define DEC_MIN_EMAX 092+ #define DEC_MAX_EMIN 093+ #define DEC_MIN_EMIN -99999999994+ #define DEC_MAX_MATH 999999 /* max emax, etc., for math funcs. */95+96+ /* Classifications for decimal numbers, aligned with 754 (note that */97+ /* 'normal' and 'subnormal' are meaningful only with a decContext */98+ /* or a fixed size format). */99+ enum decClass {100+ DEC_CLASS_SNAN,101+ DEC_CLASS_QNAN,102+ DEC_CLASS_NEG_INF,103+ DEC_CLASS_NEG_NORMAL,104+ DEC_CLASS_NEG_SUBNORMAL,105+ DEC_CLASS_NEG_ZERO,106+ DEC_CLASS_POS_ZERO,107+ DEC_CLASS_POS_SUBNORMAL,108+ DEC_CLASS_POS_NORMAL,109+ DEC_CLASS_POS_INF110+ };111+ /* Strings for the decClasses */112+ #define DEC_ClassString_SN "sNaN"113+ #define DEC_ClassString_QN "NaN"114+ #define DEC_ClassString_NI "-Infinity"115+ #define DEC_ClassString_NN "-Normal"116+ #define DEC_ClassString_NS "-Subnormal"117+ #define DEC_ClassString_NZ "-Zero"118+ #define DEC_ClassString_PZ "+Zero"119+ #define DEC_ClassString_PS "+Subnormal"120+ #define DEC_ClassString_PN "+Normal"121+ #define DEC_ClassString_PI "+Infinity"122+ #define DEC_ClassString_UN "Invalid"123+124+ /* Trap-enabler and Status flags (exceptional conditions), and */125+ /* their names. The top byte is reserved for internal use */126+ #if DECEXTFLAG127+ /* Extended flags */128+ #define DEC_Conversion_syntax 0x00000001129+ #define DEC_Division_by_zero 0x00000002130+ #define DEC_Division_impossible 0x00000004131+ #define DEC_Division_undefined 0x00000008132+ #define DEC_Insufficient_storage 0x00000010 /* [when malloc fails] */133+ #define DEC_Inexact 0x00000020134+ #define DEC_Invalid_context 0x00000040135+ #define DEC_Invalid_operation 0x00000080136+ #if DECSUBSET137+ #define DEC_Lost_digits 0x00000100138+ #endif139+ #define DEC_Overflow 0x00000200140+ #define DEC_Clamped 0x00000400141+ #define DEC_Rounded 0x00000800142+ #define DEC_Subnormal 0x00001000143+ #define DEC_Underflow 0x00002000144+ #else145+ /* IEEE flags only */146+ #define DEC_Conversion_syntax 0x00000010147+ #define DEC_Division_by_zero 0x00000002148+ #define DEC_Division_impossible 0x00000010149+ #define DEC_Division_undefined 0x00000010150+ #define DEC_Insufficient_storage 0x00000010 /* [when malloc fails] */151+ #define DEC_Inexact 0x00000001152+ #define DEC_Invalid_context 0x00000010153+ #define DEC_Invalid_operation 0x00000010154+ #if DECSUBSET155+ #define DEC_Lost_digits 0x00000000156+ #endif157+ #define DEC_Overflow 0x00000008158+ #define DEC_Clamped 0x00000000159+ #define DEC_Rounded 0x00000000160+ #define DEC_Subnormal 0x00000000161+ #define DEC_Underflow 0x00000004162+ #endif163+164+ /* IEEE 754 groupings for the flags */165+ /* [DEC_Clamped, DEC_Lost_digits, DEC_Rounded, and DEC_Subnormal */166+ /* are not in IEEE 754] */167+ #define DEC_IEEE_754_Division_by_zero (DEC_Division_by_zero)168+ #if DECSUBSET169+ #define DEC_IEEE_754_Inexact (DEC_Inexact | DEC_Lost_digits)170+ #else171+ #define DEC_IEEE_754_Inexact (DEC_Inexact)172+ #endif173+ #define DEC_IEEE_754_Invalid_operation (DEC_Conversion_syntax | \174+ DEC_Division_impossible | \175+ DEC_Division_undefined | \176+ DEC_Insufficient_storage | \177+ DEC_Invalid_context | \178+ DEC_Invalid_operation)179+ #define DEC_IEEE_754_Overflow (DEC_Overflow)180+ #define DEC_IEEE_754_Underflow (DEC_Underflow)181+182+ /* flags which are normally errors (result is qNaN, infinite, or 0) */183+ #define DEC_Errors (DEC_IEEE_754_Division_by_zero | \184+ DEC_IEEE_754_Invalid_operation | \185+ DEC_IEEE_754_Overflow | DEC_IEEE_754_Underflow)186+ /* flags which cause a result to become qNaN */187+ #define DEC_NaNs DEC_IEEE_754_Invalid_operation188+189+ /* flags which are normally for information only (finite results) */190+ #if DECSUBSET191+ #define DEC_Information (DEC_Clamped | DEC_Rounded | DEC_Inexact \192+ | DEC_Lost_digits)193+ #else194+ #define DEC_Information (DEC_Clamped | DEC_Rounded | DEC_Inexact)195+ #endif196+197+ /* IEEE 854 names (for compatibility with older decNumber versions) */198+ #define DEC_IEEE_854_Division_by_zero DEC_IEEE_754_Division_by_zero199+ #define DEC_IEEE_854_Inexact DEC_IEEE_754_Inexact200+ #define DEC_IEEE_854_Invalid_operation DEC_IEEE_754_Invalid_operation201+ #define DEC_IEEE_854_Overflow DEC_IEEE_754_Overflow202+ #define DEC_IEEE_854_Underflow DEC_IEEE_754_Underflow203+204+ /* Name strings for the exceptional conditions */205+ #define DEC_Condition_CS "Conversion syntax"206+ #define DEC_Condition_DZ "Division by zero"207+ #define DEC_Condition_DI "Division impossible"208+ #define DEC_Condition_DU "Division undefined"209+ #define DEC_Condition_IE "Inexact"210+ #define DEC_Condition_IS "Insufficient storage"211+ #define DEC_Condition_IC "Invalid context"212+ #define DEC_Condition_IO "Invalid operation"213+ #if DECSUBSET214+ #define DEC_Condition_LD "Lost digits"215+ #endif216+ #define DEC_Condition_OV "Overflow"217+ #define DEC_Condition_PA "Clamped"218+ #define DEC_Condition_RO "Rounded"219+ #define DEC_Condition_SU "Subnormal"220+ #define DEC_Condition_UN "Underflow"221+ #define DEC_Condition_ZE "No status"222+ #define DEC_Condition_MU "Multiple status"223+ #define DEC_Condition_Length 21 /* length of the longest string, */224+ /* including terminator */225+226+ /* Initialization descriptors, used by decContextDefault */227+ #define DEC_INIT_BASE 0228+ #define DEC_INIT_DECIMAL32 32229+ #define DEC_INIT_DECIMAL64 64230+ #define DEC_INIT_DECIMAL128 128231+ /* Synonyms */232+ #define DEC_INIT_DECSINGLE DEC_INIT_DECIMAL32233+ #define DEC_INIT_DECDOUBLE DEC_INIT_DECIMAL64234+ #define DEC_INIT_DECQUAD DEC_INIT_DECIMAL128235+236+ /* decContext routines */237+ extern decContext * decContextClearStatus(decContext *, uint32_t);238+ extern decContext * decContextDefault(decContext *, int32_t);239+ extern enum rounding decContextGetRounding(decContext *);240+ extern uint32_t decContextGetStatus(decContext *);241+ extern decContext * decContextRestoreStatus(decContext *, uint32_t, uint32_t);242+ extern uint32_t decContextSaveStatus(decContext *, uint32_t);243+ extern decContext * decContextSetRounding(decContext *, enum rounding);244+ extern decContext * decContextSetStatus(decContext *, uint32_t);245+ extern decContext * decContextSetStatusFromString(decContext *, const char *);246+ extern decContext * decContextSetStatusFromStringQuiet(decContext *, const char *);247+ extern decContext * decContextSetStatusQuiet(decContext *, uint32_t);248+ extern const char * decContextStatusToString(const decContext *);249+ extern int32_t decContextTestEndian(uint8_t);250+ extern uint32_t decContextTestSavedStatus(uint32_t, uint32_t);251+ extern uint32_t decContextTestStatus(decContext *, uint32_t);252+ extern decContext * decContextZeroStatus(decContext *);253+254+#endifadded:src/decNumber/decDouble.c+140 added
1+/* ------------------------------------------------------------------ */2+/* decDouble.c -- decDouble operations module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises decDouble operations (including conversions) */20+/* ------------------------------------------------------------------ */21+22+#include "decContext.h" // public includes23+#include "decDouble.h" // ..24+25+/* Constant mappings for shared code */26+#define DECPMAX DECDOUBLE_Pmax27+#define DECEMIN DECDOUBLE_Emin28+#define DECEMAX DECDOUBLE_Emax29+#define DECEMAXD DECDOUBLE_EmaxD30+#define DECBYTES DECDOUBLE_Bytes31+#define DECSTRING DECDOUBLE_String32+#define DECECONL DECDOUBLE_EconL33+#define DECBIAS DECDOUBLE_Bias34+#define DECLETS DECDOUBLE_Declets35+#define DECQTINY (-DECDOUBLE_Bias)36+// parameters of next-wider format37+#define DECWBYTES DECQUAD_Bytes38+#define DECWPMAX DECQUAD_Pmax39+#define DECWECONL DECQUAD_EconL40+#define DECWBIAS DECQUAD_Bias41+42+/* Type and function mappings for shared code */43+#define decFloat decDouble // Type name44+#define decFloatWider decQuad // Type name45+46+// Utilities and conversions (binary results, extractors, etc.)47+#define decFloatFromBCD decDoubleFromBCD48+#define decFloatFromInt32 decDoubleFromInt3249+#define decFloatFromPacked decDoubleFromPacked50+#define decFloatFromPackedChecked decDoubleFromPackedChecked51+#define decFloatFromString decDoubleFromString52+#define decFloatFromUInt32 decDoubleFromUInt3253+#define decFloatFromWider decDoubleFromWider54+#define decFloatGetCoefficient decDoubleGetCoefficient55+#define decFloatGetExponent decDoubleGetExponent56+#define decFloatSetCoefficient decDoubleSetCoefficient57+#define decFloatSetExponent decDoubleSetExponent58+#define decFloatShow decDoubleShow59+#define decFloatToBCD decDoubleToBCD60+#define decFloatToEngString decDoubleToEngString61+#define decFloatToInt32 decDoubleToInt3262+#define decFloatToInt32Exact decDoubleToInt32Exact63+#define decFloatToPacked decDoubleToPacked64+#define decFloatToString decDoubleToString65+#define decFloatToUInt32 decDoubleToUInt3266+#define decFloatToUInt32Exact decDoubleToUInt32Exact67+#define decFloatToWider decDoubleToWider68+#define decFloatZero decDoubleZero69+70+// Computational (result is a decFloat)71+#define decFloatAbs decDoubleAbs72+#define decFloatAdd decDoubleAdd73+#define decFloatAnd decDoubleAnd74+#define decFloatDivide decDoubleDivide75+#define decFloatDivideInteger decDoubleDivideInteger76+#define decFloatFMA decDoubleFMA77+#define decFloatInvert decDoubleInvert78+#define decFloatLogB decDoubleLogB79+#define decFloatMax decDoubleMax80+#define decFloatMaxMag decDoubleMaxMag81+#define decFloatMin decDoubleMin82+#define decFloatMinMag decDoubleMinMag83+#define decFloatMinus decDoubleMinus84+#define decFloatMultiply decDoubleMultiply85+#define decFloatNextMinus decDoubleNextMinus86+#define decFloatNextPlus decDoubleNextPlus87+#define decFloatNextToward decDoubleNextToward88+#define decFloatOr decDoubleOr89+#define decFloatPlus decDoublePlus90+#define decFloatQuantize decDoubleQuantize91+#define decFloatReduce decDoubleReduce92+#define decFloatRemainder decDoubleRemainder93+#define decFloatRemainderNear decDoubleRemainderNear94+#define decFloatRotate decDoubleRotate95+#define decFloatScaleB decDoubleScaleB96+#define decFloatShift decDoubleShift97+#define decFloatSubtract decDoubleSubtract98+#define decFloatToIntegralValue decDoubleToIntegralValue99+#define decFloatToIntegralExact decDoubleToIntegralExact100+#define decFloatXor decDoubleXor101+102+// Comparisons103+#define decFloatCompare decDoubleCompare104+#define decFloatCompareSignal decDoubleCompareSignal105+#define decFloatCompareTotal decDoubleCompareTotal106+#define decFloatCompareTotalMag decDoubleCompareTotalMag107+108+// Copies109+#define decFloatCanonical decDoubleCanonical110+#define decFloatCopy decDoubleCopy111+#define decFloatCopyAbs decDoubleCopyAbs112+#define decFloatCopyNegate decDoubleCopyNegate113+#define decFloatCopySign decDoubleCopySign114+115+// Non-computational116+#define decFloatClass decDoubleClass117+#define decFloatClassString decDoubleClassString118+#define decFloatDigits decDoubleDigits119+#define decFloatIsCanonical decDoubleIsCanonical120+#define decFloatIsFinite decDoubleIsFinite121+#define decFloatIsInfinite decDoubleIsInfinite122+#define decFloatIsInteger decDoubleIsInteger123+#define decFloatIsLogical decDoubleIsLogical124+#define decFloatIsNaN decDoubleIsNaN125+#define decFloatIsNegative decDoubleIsNegative126+#define decFloatIsNormal decDoubleIsNormal127+#define decFloatIsPositive decDoubleIsPositive128+#define decFloatIsSignaling decDoubleIsSignaling129+#define decFloatIsSignalling decDoubleIsSignalling130+#define decFloatIsSigned decDoubleIsSigned131+#define decFloatIsSubnormal decDoubleIsSubnormal132+#define decFloatIsZero decDoubleIsZero133+#define decFloatRadix decDoubleRadix134+#define decFloatSameQuantum decDoubleSameQuantum135+#define decFloatVersion decDoubleVersion136+137+#include "decNumberLocal.h" // local includes (need DECPMAX)138+#include "decCommon.c" // non-arithmetic decFloat routines139+#include "decBasic.c" // basic formats routines140+added:src/decNumber/decDouble.h+155 added
1+/* ------------------------------------------------------------------ */2+/* decDouble.h -- Decimal 64-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECDOUBLE)21+ #define DECDOUBLE22+23+ #define DECDOUBLENAME "decimalDouble" /* Short name */24+ #define DECDOUBLETITLE "Decimal 64-bit datum" /* Verbose name */25+ #define DECDOUBLEAUTHOR "Mike Cowlishaw" /* Who to blame */26+27+ /* parameters for decDoubles */28+ #define DECDOUBLE_Bytes 8 /* length */29+ #define DECDOUBLE_Pmax 16 /* maximum precision (digits) */30+ #define DECDOUBLE_Emin -383 /* minimum adjusted exponent */31+ #define DECDOUBLE_Emax 384 /* maximum adjusted exponent */32+ #define DECDOUBLE_EmaxD 3 /* maximum exponent digits */33+ #define DECDOUBLE_Bias 398 /* bias for the exponent */34+ #define DECDOUBLE_String 25 /* maximum string length, +1 */35+ #define DECDOUBLE_EconL 8 /* exponent continuation length */36+ #define DECDOUBLE_Declets 5 /* count of declets */37+ /* highest biased exponent (Elimit-1) */38+ #define DECDOUBLE_Ehigh (DECDOUBLE_Emax + DECDOUBLE_Bias - (DECDOUBLE_Pmax-1))39+40+ /* Required includes */41+ #include "decContext.h"42+ #include "decQuad.h"43+44+ /* The decDouble decimal 64-bit type, accessible by all sizes */45+ typedef union {46+ uint8_t bytes[DECDOUBLE_Bytes]; /* fields: 1, 5, 8, 50 bits */47+ uint16_t shorts[DECDOUBLE_Bytes/2];48+ uint32_t words[DECDOUBLE_Bytes/4];49+ #if DECUSE6450+ uint64_t longs[DECDOUBLE_Bytes/8];51+ #endif52+ } decDouble;53+54+ /* ---------------------------------------------------------------- */55+ /* Routines -- implemented as decFloat routines in common files */56+ /* ---------------------------------------------------------------- */57+58+ /* Utilities and conversions, extractors, etc.) */59+ extern decDouble * decDoubleFromBCD(decDouble *, int32_t, const uint8_t *, int32_t);60+ extern decDouble * decDoubleFromInt32(decDouble *, int32_t);61+ extern decDouble * decDoubleFromPacked(decDouble *, int32_t, const uint8_t *);62+ extern decDouble * decDoubleFromPackedChecked(decDouble *, int32_t, const uint8_t *);63+ extern decDouble * decDoubleFromString(decDouble *, const char *, decContext *);64+ extern decDouble * decDoubleFromUInt32(decDouble *, uint32_t);65+ extern decDouble * decDoubleFromWider(decDouble *, const decQuad *, decContext *);66+ extern int32_t decDoubleGetCoefficient(const decDouble *, uint8_t *);67+ extern int32_t decDoubleGetExponent(const decDouble *);68+ extern decDouble * decDoubleSetCoefficient(decDouble *, const uint8_t *, int32_t);69+ extern decDouble * decDoubleSetExponent(decDouble *, decContext *, int32_t);70+ extern void decDoubleShow(const decDouble *, const char *);71+ extern int32_t decDoubleToBCD(const decDouble *, int32_t *, uint8_t *);72+ extern char * decDoubleToEngString(const decDouble *, char *);73+ extern int32_t decDoubleToInt32(const decDouble *, decContext *, enum rounding);74+ extern int32_t decDoubleToInt32Exact(const decDouble *, decContext *, enum rounding);75+ extern int32_t decDoubleToPacked(const decDouble *, int32_t *, uint8_t *);76+ extern char * decDoubleToString(const decDouble *, char *);77+ extern uint32_t decDoubleToUInt32(const decDouble *, decContext *, enum rounding);78+ extern uint32_t decDoubleToUInt32Exact(const decDouble *, decContext *, enum rounding);79+ extern decQuad * decDoubleToWider(const decDouble *, decQuad *);80+ extern decDouble * decDoubleZero(decDouble *);81+82+ /* Computational (result is a decDouble) */83+ extern decDouble * decDoubleAbs(decDouble *, const decDouble *, decContext *);84+ extern decDouble * decDoubleAdd(decDouble *, const decDouble *, const decDouble *, decContext *);85+ extern decDouble * decDoubleAnd(decDouble *, const decDouble *, const decDouble *, decContext *);86+ extern decDouble * decDoubleDivide(decDouble *, const decDouble *, const decDouble *, decContext *);87+ extern decDouble * decDoubleDivideInteger(decDouble *, const decDouble *, const decDouble *, decContext *);88+ extern decDouble * decDoubleFMA(decDouble *, const decDouble *, const decDouble *, const decDouble *, decContext *);89+ extern decDouble * decDoubleInvert(decDouble *, const decDouble *, decContext *);90+ extern decDouble * decDoubleLogB(decDouble *, const decDouble *, decContext *);91+ extern decDouble * decDoubleMax(decDouble *, const decDouble *, const decDouble *, decContext *);92+ extern decDouble * decDoubleMaxMag(decDouble *, const decDouble *, const decDouble *, decContext *);93+ extern decDouble * decDoubleMin(decDouble *, const decDouble *, const decDouble *, decContext *);94+ extern decDouble * decDoubleMinMag(decDouble *, const decDouble *, const decDouble *, decContext *);95+ extern decDouble * decDoubleMinus(decDouble *, const decDouble *, decContext *);96+ extern decDouble * decDoubleMultiply(decDouble *, const decDouble *, const decDouble *, decContext *);97+ extern decDouble * decDoubleNextMinus(decDouble *, const decDouble *, decContext *);98+ extern decDouble * decDoubleNextPlus(decDouble *, const decDouble *, decContext *);99+ extern decDouble * decDoubleNextToward(decDouble *, const decDouble *, const decDouble *, decContext *);100+ extern decDouble * decDoubleOr(decDouble *, const decDouble *, const decDouble *, decContext *);101+ extern decDouble * decDoublePlus(decDouble *, const decDouble *, decContext *);102+ extern decDouble * decDoubleQuantize(decDouble *, const decDouble *, const decDouble *, decContext *);103+ extern decDouble * decDoubleReduce(decDouble *, const decDouble *, decContext *);104+ extern decDouble * decDoubleRemainder(decDouble *, const decDouble *, const decDouble *, decContext *);105+ extern decDouble * decDoubleRemainderNear(decDouble *, const decDouble *, const decDouble *, decContext *);106+ extern decDouble * decDoubleRotate(decDouble *, const decDouble *, const decDouble *, decContext *);107+ extern decDouble * decDoubleScaleB(decDouble *, const decDouble *, const decDouble *, decContext *);108+ extern decDouble * decDoubleShift(decDouble *, const decDouble *, const decDouble *, decContext *);109+ extern decDouble * decDoubleSubtract(decDouble *, const decDouble *, const decDouble *, decContext *);110+ extern decDouble * decDoubleToIntegralValue(decDouble *, const decDouble *, decContext *, enum rounding);111+ extern decDouble * decDoubleToIntegralExact(decDouble *, const decDouble *, decContext *);112+ extern decDouble * decDoubleXor(decDouble *, const decDouble *, const decDouble *, decContext *);113+114+ /* Comparisons */115+ extern decDouble * decDoubleCompare(decDouble *, const decDouble *, const decDouble *, decContext *);116+ extern decDouble * decDoubleCompareSignal(decDouble *, const decDouble *, const decDouble *, decContext *);117+ extern decDouble * decDoubleCompareTotal(decDouble *, const decDouble *, const decDouble *);118+ extern decDouble * decDoubleCompareTotalMag(decDouble *, const decDouble *, const decDouble *);119+120+ /* Copies */121+ extern decDouble * decDoubleCanonical(decDouble *, const decDouble *);122+ extern decDouble * decDoubleCopy(decDouble *, const decDouble *);123+ extern decDouble * decDoubleCopyAbs(decDouble *, const decDouble *);124+ extern decDouble * decDoubleCopyNegate(decDouble *, const decDouble *);125+ extern decDouble * decDoubleCopySign(decDouble *, const decDouble *, const decDouble *);126+127+ /* Non-computational */128+ extern enum decClass decDoubleClass(const decDouble *);129+ extern const char * decDoubleClassString(const decDouble *);130+ extern uint32_t decDoubleDigits(const decDouble *);131+ extern uint32_t decDoubleIsCanonical(const decDouble *);132+ extern uint32_t decDoubleIsFinite(const decDouble *);133+ extern uint32_t decDoubleIsInfinite(const decDouble *);134+ extern uint32_t decDoubleIsInteger(const decDouble *);135+ extern uint32_t decDoubleIsLogical(const decDouble *);136+ extern uint32_t decDoubleIsNaN(const decDouble *);137+ extern uint32_t decDoubleIsNegative(const decDouble *);138+ extern uint32_t decDoubleIsNormal(const decDouble *);139+ extern uint32_t decDoubleIsPositive(const decDouble *);140+ extern uint32_t decDoubleIsSignaling(const decDouble *);141+ extern uint32_t decDoubleIsSignalling(const decDouble *);142+ extern uint32_t decDoubleIsSigned(const decDouble *);143+ extern uint32_t decDoubleIsSubnormal(const decDouble *);144+ extern uint32_t decDoubleIsZero(const decDouble *);145+ extern uint32_t decDoubleRadix(const decDouble *);146+ extern uint32_t decDoubleSameQuantum(const decDouble *, const decDouble *);147+ extern const char * decDoubleVersion(void);148+149+ /* decNumber conversions; these are implemented as macros so as not */150+ /* to force a dependency on decimal64 and decNumber in decDouble. */151+ /* decDoubleFromNumber returns a decimal64 * to avoid warnings. */152+ #define decDoubleToNumber(dq, dn) decimal64ToNumber((decimal64 *)(dq), dn)153+ #define decDoubleFromNumber(dq, dn, set) decimal64FromNumber((decimal64 *)(dq), dn, set)154+155+#endifadded:src/decNumber/decDPD.h+1185 added
1+/* ------------------------------------------------------------------------ */2+/* Binary Coded Decimal and Densely Packed Decimal conversion lookup tables */3+/* [Automatically generated -- do not edit. 2008.06.21] */4+/* ------------------------------------------------------------------------ */5+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */6+/* ------------------------------------------------------------------------ */7+/* For details, see DPDecimal.html on the General Decimal Arithmetic page. */8+/* */9+/* This include file defines several DPD and BCD conversion tables: */10+/* */11+/* uint16_t BCD2DPD[2458]; -- BCD -> DPD (0x999 => 2457) */12+/* uint16_t BIN2DPD[1000]; -- Bin -> DPD (999 => 2457) */13+/* uint8_t BIN2CHAR[4001]; -- Bin -> CHAR (999 => '\3' '9' '9' '9') */14+/* uint8_t BIN2BCD8[4000]; -- Bin -> bytes (999 => 9 9 9 3) */15+/* uint16_t DPD2BCD[1024]; -- DPD -> BCD (0x3FF => 0x999) */16+/* uint16_t DPD2BIN[1024]; -- DPD -> BIN (0x3FF => 999) */17+/* uint32_t DPD2BINK[1024]; -- DPD -> BIN * 1000 (0x3FF => 999000) */18+/* uint32_t DPD2BINM[1024]; -- DPD -> BIN * 1E+6 (0x3FF => 999000000) */19+/* uint8_t DPD2BCD8[4096]; -- DPD -> bytes (x3FF => 9 9 9 3) */20+/* */21+/* In all cases the result (10 bits or 12 bits, or binary) is right-aligned */22+/* in the table entry. BIN2CHAR entries are a single byte length (0 for */23+/* value 0) followed by three digit characters; a trailing terminator is */24+/* included to allow 4-char moves always. BIN2BCD8 and DPD2BCD8 entries */25+/* are similar with the three BCD8 digits followed by a one-byte length */26+/* (again, length=0 for value 0). */27+/* */28+/* To use a table, its name, prefixed with DEC_, must be defined with a */29+/* value of 1 before this header file is included. For example: */30+/* #define DEC_BCD2DPD 1 */31+/* This mechanism allows software to only include tables that are needed. */32+/* ------------------------------------------------------------------------ */33+ 34+#if defined(DEC_BCD2DPD) && DEC_BCD2DPD==1 && !defined(DECBCD2DPD)35+#define DECBCD2DPD36+ 37+const uint16_t BCD2DPD[2458]={ 0, 1, 2, 3, 4, 5, 6, 7, 38+ 8, 9, 0, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 39+ 21, 22, 23, 24, 25, 0, 0, 0, 0, 0, 0, 32, 33, 40+ 34, 35, 36, 37, 38, 39, 40, 41, 0, 0, 0, 0, 0, 41+ 0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 0, 42+ 0, 0, 0, 0, 64, 65, 66, 67, 68, 69, 70, 71, 72, 43+ 73, 0, 0, 0, 0, 0, 0, 80, 81, 82, 83, 84, 85, 44+ 86, 87, 88, 89, 0, 0, 0, 0, 0, 0, 96, 97, 98, 45+ 99, 100, 101, 102, 103, 104, 105, 0, 0, 0, 0, 0, 0, 46+ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 0, 0, 0, 47+ 0, 0, 0, 10, 11, 42, 43, 74, 75, 106, 107, 78, 79, 48+ 0, 0, 0, 0, 0, 0, 26, 27, 58, 59, 90, 91, 122, 49+ 123, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 52+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 55+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 57+ 0, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 0, 0, 58+ 0, 0, 0, 0, 144, 145, 146, 147, 148, 149, 150, 151, 152, 59+ 153, 0, 0, 0, 0, 0, 0, 160, 161, 162, 163, 164, 165, 60+ 166, 167, 168, 169, 0, 0, 0, 0, 0, 0, 176, 177, 178, 61+ 179, 180, 181, 182, 183, 184, 185, 0, 0, 0, 0, 0, 0, 62+ 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 0, 0, 0, 63+ 0, 0, 0, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 64+ 0, 0, 0, 0, 0, 0, 224, 225, 226, 227, 228, 229, 230, 65+ 231, 232, 233, 0, 0, 0, 0, 0, 0, 240, 241, 242, 243, 66+ 244, 245, 246, 247, 248, 249, 0, 0, 0, 0, 0, 0, 138, 67+ 139, 170, 171, 202, 203, 234, 235, 206, 207, 0, 0, 0, 0, 68+ 0, 0, 154, 155, 186, 187, 218, 219, 250, 251, 222, 223, 0, 69+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 72+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 73+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 75+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 76+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 256, 257, 258, 77+ 259, 260, 261, 262, 263, 264, 265, 0, 0, 0, 0, 0, 0, 78+ 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 0, 0, 0, 79+ 0, 0, 0, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 80+ 0, 0, 0, 0, 0, 0, 304, 305, 306, 307, 308, 309, 310, 81+ 311, 312, 313, 0, 0, 0, 0, 0, 0, 320, 321, 322, 323, 82+ 324, 325, 326, 327, 328, 329, 0, 0, 0, 0, 0, 0, 336, 83+ 337, 338, 339, 340, 341, 342, 343, 344, 345, 0, 0, 0, 0, 84+ 0, 0, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 0, 85+ 0, 0, 0, 0, 0, 368, 369, 370, 371, 372, 373, 374, 375, 86+ 376, 377, 0, 0, 0, 0, 0, 0, 266, 267, 298, 299, 330, 87+ 331, 362, 363, 334, 335, 0, 0, 0, 0, 0, 0, 282, 283, 88+ 314, 315, 346, 347, 378, 379, 350, 351, 0, 0, 0, 0, 0, 89+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 90+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 91+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 93+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 94+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96+ 0, 0, 0, 0, 0, 0, 384, 385, 386, 387, 388, 389, 390, 97+ 391, 392, 393, 0, 0, 0, 0, 0, 0, 400, 401, 402, 403, 98+ 404, 405, 406, 407, 408, 409, 0, 0, 0, 0, 0, 0, 416, 99+ 417, 418, 419, 420, 421, 422, 423, 424, 425, 0, 0, 0, 0, 100+ 0, 0, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 0, 101+ 0, 0, 0, 0, 0, 448, 449, 450, 451, 452, 453, 454, 455, 102+ 456, 457, 0, 0, 0, 0, 0, 0, 464, 465, 466, 467, 468, 103+ 469, 470, 471, 472, 473, 0, 0, 0, 0, 0, 0, 480, 481, 104+ 482, 483, 484, 485, 486, 487, 488, 489, 0, 0, 0, 0, 0, 105+ 0, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 0, 0, 106+ 0, 0, 0, 0, 394, 395, 426, 427, 458, 459, 490, 491, 462, 107+ 463, 0, 0, 0, 0, 0, 0, 410, 411, 442, 443, 474, 475, 108+ 506, 507, 478, 479, 0, 0, 0, 0, 0, 0, 0, 0, 0, 109+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 110+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 111+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 112+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 113+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 114+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 115+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116+ 0, 0, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 0, 117+ 0, 0, 0, 0, 0, 528, 529, 530, 531, 532, 533, 534, 535, 118+ 536, 537, 0, 0, 0, 0, 0, 0, 544, 545, 546, 547, 548, 119+ 549, 550, 551, 552, 553, 0, 0, 0, 0, 0, 0, 560, 561, 120+ 562, 563, 564, 565, 566, 567, 568, 569, 0, 0, 0, 0, 0, 121+ 0, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 0, 0, 122+ 0, 0, 0, 0, 592, 593, 594, 595, 596, 597, 598, 599, 600, 123+ 601, 0, 0, 0, 0, 0, 0, 608, 609, 610, 611, 612, 613, 124+ 614, 615, 616, 617, 0, 0, 0, 0, 0, 0, 624, 625, 626, 125+ 627, 628, 629, 630, 631, 632, 633, 0, 0, 0, 0, 0, 0, 126+ 522, 523, 554, 555, 586, 587, 618, 619, 590, 591, 0, 0, 0, 127+ 0, 0, 0, 538, 539, 570, 571, 602, 603, 634, 635, 606, 607, 128+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 129+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 130+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 131+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 132+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 133+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 134+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 135+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 640, 641, 136+ 642, 643, 644, 645, 646, 647, 648, 649, 0, 0, 0, 0, 0, 137+ 0, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 0, 0, 138+ 0, 0, 0, 0, 672, 673, 674, 675, 676, 677, 678, 679, 680, 139+ 681, 0, 0, 0, 0, 0, 0, 688, 689, 690, 691, 692, 693, 140+ 694, 695, 696, 697, 0, 0, 0, 0, 0, 0, 704, 705, 706, 141+ 707, 708, 709, 710, 711, 712, 713, 0, 0, 0, 0, 0, 0, 142+ 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 0, 0, 0, 143+ 0, 0, 0, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 144+ 0, 0, 0, 0, 0, 0, 752, 753, 754, 755, 756, 757, 758, 145+ 759, 760, 761, 0, 0, 0, 0, 0, 0, 650, 651, 682, 683, 146+ 714, 715, 746, 747, 718, 719, 0, 0, 0, 0, 0, 0, 666, 147+ 667, 698, 699, 730, 731, 762, 763, 734, 735, 0, 0, 0, 0, 148+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 149+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 150+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 151+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 152+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 153+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 154+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 155+ 0, 0, 0, 0, 0, 0, 0, 768, 769, 770, 771, 772, 773, 156+ 774, 775, 776, 777, 0, 0, 0, 0, 0, 0, 784, 785, 786, 157+ 787, 788, 789, 790, 791, 792, 793, 0, 0, 0, 0, 0, 0, 158+ 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 0, 0, 0, 159+ 0, 0, 0, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 160+ 0, 0, 0, 0, 0, 0, 832, 833, 834, 835, 836, 837, 838, 161+ 839, 840, 841, 0, 0, 0, 0, 0, 0, 848, 849, 850, 851, 162+ 852, 853, 854, 855, 856, 857, 0, 0, 0, 0, 0, 0, 864, 163+ 865, 866, 867, 868, 869, 870, 871, 872, 873, 0, 0, 0, 0, 164+ 0, 0, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 0, 165+ 0, 0, 0, 0, 0, 778, 779, 810, 811, 842, 843, 874, 875, 166+ 846, 847, 0, 0, 0, 0, 0, 0, 794, 795, 826, 827, 858, 167+ 859, 890, 891, 862, 863, 0, 0, 0, 0, 0, 0, 0, 0, 168+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 169+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 170+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 171+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 173+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 174+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 175+ 0, 0, 0, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 176+ 0, 0, 0, 0, 0, 0, 912, 913, 914, 915, 916, 917, 918, 177+ 919, 920, 921, 0, 0, 0, 0, 0, 0, 928, 929, 930, 931, 178+ 932, 933, 934, 935, 936, 937, 0, 0, 0, 0, 0, 0, 944, 179+ 945, 946, 947, 948, 949, 950, 951, 952, 953, 0, 0, 0, 0, 180+ 0, 0, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 0, 181+ 0, 0, 0, 0, 0, 976, 977, 978, 979, 980, 981, 982, 983, 182+ 984, 985, 0, 0, 0, 0, 0, 0, 992, 993, 994, 995, 996, 183+ 997, 998, 999, 1000, 1001, 0, 0, 0, 0, 0, 0, 1008, 1009, 184+ 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 0, 0, 0, 0, 0, 185+ 0, 906, 907, 938, 939, 970, 971, 1002, 1003, 974, 975, 0, 0, 186+ 0, 0, 0, 0, 922, 923, 954, 955, 986, 987, 1018, 1019, 990, 187+ 991, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 188+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 189+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 190+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 191+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 193+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 194+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 195+ 13, 268, 269, 524, 525, 780, 781, 46, 47, 0, 0, 0, 0, 196+ 0, 0, 28, 29, 284, 285, 540, 541, 796, 797, 62, 63, 0, 197+ 0, 0, 0, 0, 0, 44, 45, 300, 301, 556, 557, 812, 813, 198+ 302, 303, 0, 0, 0, 0, 0, 0, 60, 61, 316, 317, 572, 199+ 573, 828, 829, 318, 319, 0, 0, 0, 0, 0, 0, 76, 77, 200+ 332, 333, 588, 589, 844, 845, 558, 559, 0, 0, 0, 0, 0, 201+ 0, 92, 93, 348, 349, 604, 605, 860, 861, 574, 575, 0, 0, 202+ 0, 0, 0, 0, 108, 109, 364, 365, 620, 621, 876, 877, 814, 203+ 815, 0, 0, 0, 0, 0, 0, 124, 125, 380, 381, 636, 637, 204+ 892, 893, 830, 831, 0, 0, 0, 0, 0, 0, 14, 15, 270, 205+ 271, 526, 527, 782, 783, 110, 111, 0, 0, 0, 0, 0, 0, 206+ 30, 31, 286, 287, 542, 543, 798, 799, 126, 127, 0, 0, 0, 207+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 208+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 210+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 211+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 212+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 213+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 214+ 0, 0, 0, 0, 0, 0, 0, 0, 140, 141, 396, 397, 652, 215+ 653, 908, 909, 174, 175, 0, 0, 0, 0, 0, 0, 156, 157, 216+ 412, 413, 668, 669, 924, 925, 190, 191, 0, 0, 0, 0, 0, 217+ 0, 172, 173, 428, 429, 684, 685, 940, 941, 430, 431, 0, 0, 218+ 0, 0, 0, 0, 188, 189, 444, 445, 700, 701, 956, 957, 446, 219+ 447, 0, 0, 0, 0, 0, 0, 204, 205, 460, 461, 716, 717, 220+ 972, 973, 686, 687, 0, 0, 0, 0, 0, 0, 220, 221, 476, 221+ 477, 732, 733, 988, 989, 702, 703, 0, 0, 0, 0, 0, 0, 222+ 236, 237, 492, 493, 748, 749, 1004, 1005, 942, 943, 0, 0, 0, 223+ 0, 0, 0, 252, 253, 508, 509, 764, 765, 1020, 1021, 958, 959, 224+ 0, 0, 0, 0, 0, 0, 142, 143, 398, 399, 654, 655, 910, 225+ 911, 238, 239, 0, 0, 0, 0, 0, 0, 158, 159, 414, 415, 226+ 670, 671, 926, 927, 254, 255};227+#endif228+ 229+#if defined(DEC_DPD2BCD) && DEC_DPD2BCD==1 && !defined(DECDPD2BCD)230+#define DECDPD2BCD231+ 232+const uint16_t DPD2BCD[1024]={ 0, 1, 2, 3, 4, 5, 6, 7, 233+ 8, 9, 128, 129, 2048, 2049, 2176, 2177, 16, 17, 18, 19, 20, 234+ 21, 22, 23, 24, 25, 144, 145, 2064, 2065, 2192, 2193, 32, 33, 235+ 34, 35, 36, 37, 38, 39, 40, 41, 130, 131, 2080, 2081, 2056, 236+ 2057, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 146, 147, 237+ 2096, 2097, 2072, 2073, 64, 65, 66, 67, 68, 69, 70, 71, 72, 238+ 73, 132, 133, 2112, 2113, 136, 137, 80, 81, 82, 83, 84, 85, 239+ 86, 87, 88, 89, 148, 149, 2128, 2129, 152, 153, 96, 97, 98, 240+ 99, 100, 101, 102, 103, 104, 105, 134, 135, 2144, 2145, 2184, 2185, 241+ 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 150, 151, 2160, 242+ 2161, 2200, 2201, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 243+ 384, 385, 2304, 2305, 2432, 2433, 272, 273, 274, 275, 276, 277, 278, 244+ 279, 280, 281, 400, 401, 2320, 2321, 2448, 2449, 288, 289, 290, 291, 245+ 292, 293, 294, 295, 296, 297, 386, 387, 2336, 2337, 2312, 2313, 304, 246+ 305, 306, 307, 308, 309, 310, 311, 312, 313, 402, 403, 2352, 2353, 247+ 2328, 2329, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 388, 248+ 389, 2368, 2369, 392, 393, 336, 337, 338, 339, 340, 341, 342, 343, 249+ 344, 345, 404, 405, 2384, 2385, 408, 409, 352, 353, 354, 355, 356, 250+ 357, 358, 359, 360, 361, 390, 391, 2400, 2401, 2440, 2441, 368, 369, 251+ 370, 371, 372, 373, 374, 375, 376, 377, 406, 407, 2416, 2417, 2456, 252+ 2457, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 640, 641, 253+ 2050, 2051, 2178, 2179, 528, 529, 530, 531, 532, 533, 534, 535, 536, 254+ 537, 656, 657, 2066, 2067, 2194, 2195, 544, 545, 546, 547, 548, 549, 255+ 550, 551, 552, 553, 642, 643, 2082, 2083, 2088, 2089, 560, 561, 562, 256+ 563, 564, 565, 566, 567, 568, 569, 658, 659, 2098, 2099, 2104, 2105, 257+ 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 644, 645, 2114, 258+ 2115, 648, 649, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 259+ 660, 661, 2130, 2131, 664, 665, 608, 609, 610, 611, 612, 613, 614, 260+ 615, 616, 617, 646, 647, 2146, 2147, 2184, 2185, 624, 625, 626, 627, 261+ 628, 629, 630, 631, 632, 633, 662, 663, 2162, 2163, 2200, 2201, 768, 262+ 769, 770, 771, 772, 773, 774, 775, 776, 777, 896, 897, 2306, 2307, 263+ 2434, 2435, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 912, 264+ 913, 2322, 2323, 2450, 2451, 800, 801, 802, 803, 804, 805, 806, 807, 265+ 808, 809, 898, 899, 2338, 2339, 2344, 2345, 816, 817, 818, 819, 820, 266+ 821, 822, 823, 824, 825, 914, 915, 2354, 2355, 2360, 2361, 832, 833, 267+ 834, 835, 836, 837, 838, 839, 840, 841, 900, 901, 2370, 2371, 904, 268+ 905, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 916, 917, 269+ 2386, 2387, 920, 921, 864, 865, 866, 867, 868, 869, 870, 871, 872, 270+ 873, 902, 903, 2402, 2403, 2440, 2441, 880, 881, 882, 883, 884, 885, 271+ 886, 887, 888, 889, 918, 919, 2418, 2419, 2456, 2457, 1024, 1025, 1026, 272+ 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1152, 1153, 2052, 2053, 2180, 2181, 273+ 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1168, 1169, 2068, 274+ 2069, 2196, 2197, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 275+ 1154, 1155, 2084, 2085, 2120, 2121, 1072, 1073, 1074, 1075, 1076, 1077, 1078, 276+ 1079, 1080, 1081, 1170, 1171, 2100, 2101, 2136, 2137, 1088, 1089, 1090, 1091, 277+ 1092, 1093, 1094, 1095, 1096, 1097, 1156, 1157, 2116, 2117, 1160, 1161, 1104, 278+ 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1172, 1173, 2132, 2133, 279+ 1176, 1177, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1158, 280+ 1159, 2148, 2149, 2184, 2185, 1136, 1137, 1138, 1139, 1140, 1141, 1142, 1143, 281+ 1144, 1145, 1174, 1175, 2164, 2165, 2200, 2201, 1280, 1281, 1282, 1283, 1284, 282+ 1285, 1286, 1287, 1288, 1289, 1408, 1409, 2308, 2309, 2436, 2437, 1296, 1297, 283+ 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1424, 1425, 2324, 2325, 2452, 284+ 2453, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1410, 1411, 285+ 2340, 2341, 2376, 2377, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 286+ 1337, 1426, 1427, 2356, 2357, 2392, 2393, 1344, 1345, 1346, 1347, 1348, 1349, 287+ 1350, 1351, 1352, 1353, 1412, 1413, 2372, 2373, 1416, 1417, 1360, 1361, 1362, 288+ 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1428, 1429, 2388, 2389, 1432, 1433, 289+ 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1414, 1415, 2404, 290+ 2405, 2440, 2441, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 291+ 1430, 1431, 2420, 2421, 2456, 2457, 1536, 1537, 1538, 1539, 1540, 1541, 1542, 292+ 1543, 1544, 1545, 1664, 1665, 2054, 2055, 2182, 2183, 1552, 1553, 1554, 1555, 293+ 1556, 1557, 1558, 1559, 1560, 1561, 1680, 1681, 2070, 2071, 2198, 2199, 1568, 294+ 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1666, 1667, 2086, 2087, 295+ 2152, 2153, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1682, 296+ 1683, 2102, 2103, 2168, 2169, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 297+ 1608, 1609, 1668, 1669, 2118, 2119, 1672, 1673, 1616, 1617, 1618, 1619, 1620, 298+ 1621, 1622, 1623, 1624, 1625, 1684, 1685, 2134, 2135, 1688, 1689, 1632, 1633, 299+ 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1670, 1671, 2150, 2151, 2184, 300+ 2185, 1648, 1649, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1686, 1687, 301+ 2166, 2167, 2200, 2201, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 302+ 1801, 1920, 1921, 2310, 2311, 2438, 2439, 1808, 1809, 1810, 1811, 1812, 1813, 303+ 1814, 1815, 1816, 1817, 1936, 1937, 2326, 2327, 2454, 2455, 1824, 1825, 1826, 304+ 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1922, 1923, 2342, 2343, 2408, 2409, 305+ 1840, 1841, 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, 1938, 1939, 2358, 306+ 2359, 2424, 2425, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, 307+ 1924, 1925, 2374, 2375, 1928, 1929, 1872, 1873, 1874, 1875, 1876, 1877, 1878, 308+ 1879, 1880, 1881, 1940, 1941, 2390, 2391, 1944, 1945, 1888, 1889, 1890, 1891, 309+ 1892, 1893, 1894, 1895, 1896, 1897, 1926, 1927, 2406, 2407, 2440, 2441, 1904, 310+ 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1942, 1943, 2422, 2423, 311+ 2456, 2457};312+#endif313+ 314+#if defined(DEC_BIN2DPD) && DEC_BIN2DPD==1 && !defined(DECBIN2DPD)315+#define DECBIN2DPD316+ 317+const uint16_t BIN2DPD[1000]={ 0, 1, 2, 3, 4, 5, 6, 7, 318+ 8, 9, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 32, 319+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 48, 49, 50, 51, 320+ 52, 53, 54, 55, 56, 57, 64, 65, 66, 67, 68, 69, 70, 321+ 71, 72, 73, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 322+ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 112, 113, 114, 323+ 115, 116, 117, 118, 119, 120, 121, 10, 11, 42, 43, 74, 75, 324+ 106, 107, 78, 79, 26, 27, 58, 59, 90, 91, 122, 123, 94, 325+ 95, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 144, 145, 326+ 146, 147, 148, 149, 150, 151, 152, 153, 160, 161, 162, 163, 164, 327+ 165, 166, 167, 168, 169, 176, 177, 178, 179, 180, 181, 182, 183, 328+ 184, 185, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 208, 329+ 209, 210, 211, 212, 213, 214, 215, 216, 217, 224, 225, 226, 227, 330+ 228, 229, 230, 231, 232, 233, 240, 241, 242, 243, 244, 245, 246, 331+ 247, 248, 249, 138, 139, 170, 171, 202, 203, 234, 235, 206, 207, 332+ 154, 155, 186, 187, 218, 219, 250, 251, 222, 223, 256, 257, 258, 333+ 259, 260, 261, 262, 263, 264, 265, 272, 273, 274, 275, 276, 277, 334+ 278, 279, 280, 281, 288, 289, 290, 291, 292, 293, 294, 295, 296, 335+ 297, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 320, 321, 336+ 322, 323, 324, 325, 326, 327, 328, 329, 336, 337, 338, 339, 340, 337+ 341, 342, 343, 344, 345, 352, 353, 354, 355, 356, 357, 358, 359, 338+ 360, 361, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 266, 339+ 267, 298, 299, 330, 331, 362, 363, 334, 335, 282, 283, 314, 315, 340+ 346, 347, 378, 379, 350, 351, 384, 385, 386, 387, 388, 389, 390, 341+ 391, 392, 393, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 342+ 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 432, 433, 434, 343+ 435, 436, 437, 438, 439, 440, 441, 448, 449, 450, 451, 452, 453, 344+ 454, 455, 456, 457, 464, 465, 466, 467, 468, 469, 470, 471, 472, 345+ 473, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 496, 497, 346+ 498, 499, 500, 501, 502, 503, 504, 505, 394, 395, 426, 427, 458, 347+ 459, 490, 491, 462, 463, 410, 411, 442, 443, 474, 475, 506, 507, 348+ 478, 479, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 528, 349+ 529, 530, 531, 532, 533, 534, 535, 536, 537, 544, 545, 546, 547, 350+ 548, 549, 550, 551, 552, 553, 560, 561, 562, 563, 564, 565, 566, 351+ 567, 568, 569, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 352+ 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 608, 609, 610, 353+ 611, 612, 613, 614, 615, 616, 617, 624, 625, 626, 627, 628, 629, 354+ 630, 631, 632, 633, 522, 523, 554, 555, 586, 587, 618, 619, 590, 355+ 591, 538, 539, 570, 571, 602, 603, 634, 635, 606, 607, 640, 641, 356+ 642, 643, 644, 645, 646, 647, 648, 649, 656, 657, 658, 659, 660, 357+ 661, 662, 663, 664, 665, 672, 673, 674, 675, 676, 677, 678, 679, 358+ 680, 681, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 704, 359+ 705, 706, 707, 708, 709, 710, 711, 712, 713, 720, 721, 722, 723, 360+ 724, 725, 726, 727, 728, 729, 736, 737, 738, 739, 740, 741, 742, 361+ 743, 744, 745, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 362+ 650, 651, 682, 683, 714, 715, 746, 747, 718, 719, 666, 667, 698, 363+ 699, 730, 731, 762, 763, 734, 735, 768, 769, 770, 771, 772, 773, 364+ 774, 775, 776, 777, 784, 785, 786, 787, 788, 789, 790, 791, 792, 365+ 793, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 816, 817, 366+ 818, 819, 820, 821, 822, 823, 824, 825, 832, 833, 834, 835, 836, 367+ 837, 838, 839, 840, 841, 848, 849, 850, 851, 852, 853, 854, 855, 368+ 856, 857, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 880, 369+ 881, 882, 883, 884, 885, 886, 887, 888, 889, 778, 779, 810, 811, 370+ 842, 843, 874, 875, 846, 847, 794, 795, 826, 827, 858, 859, 890, 371+ 891, 862, 863, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 372+ 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 928, 929, 930, 373+ 931, 932, 933, 934, 935, 936, 937, 944, 945, 946, 947, 948, 949, 374+ 950, 951, 952, 953, 960, 961, 962, 963, 964, 965, 966, 967, 968, 375+ 969, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 992, 993, 376+ 994, 995, 996, 997, 998, 999, 1000, 1001, 1008, 1009, 1010, 1011, 1012, 377+ 1013, 1014, 1015, 1016, 1017, 906, 907, 938, 939, 970, 971, 1002, 1003, 378+ 974, 975, 922, 923, 954, 955, 986, 987, 1018, 1019, 990, 991, 12, 379+ 13, 268, 269, 524, 525, 780, 781, 46, 47, 28, 29, 284, 285, 380+ 540, 541, 796, 797, 62, 63, 44, 45, 300, 301, 556, 557, 812, 381+ 813, 302, 303, 60, 61, 316, 317, 572, 573, 828, 829, 318, 319, 382+ 76, 77, 332, 333, 588, 589, 844, 845, 558, 559, 92, 93, 348, 383+ 349, 604, 605, 860, 861, 574, 575, 108, 109, 364, 365, 620, 621, 384+ 876, 877, 814, 815, 124, 125, 380, 381, 636, 637, 892, 893, 830, 385+ 831, 14, 15, 270, 271, 526, 527, 782, 783, 110, 111, 30, 31, 386+ 286, 287, 542, 543, 798, 799, 126, 127, 140, 141, 396, 397, 652, 387+ 653, 908, 909, 174, 175, 156, 157, 412, 413, 668, 669, 924, 925, 388+ 190, 191, 172, 173, 428, 429, 684, 685, 940, 941, 430, 431, 188, 389+ 189, 444, 445, 700, 701, 956, 957, 446, 447, 204, 205, 460, 461, 390+ 716, 717, 972, 973, 686, 687, 220, 221, 476, 477, 732, 733, 988, 391+ 989, 702, 703, 236, 237, 492, 493, 748, 749, 1004, 1005, 942, 943, 392+ 252, 253, 508, 509, 764, 765, 1020, 1021, 958, 959, 142, 143, 398, 393+ 399, 654, 655, 910, 911, 238, 239, 158, 159, 414, 415, 670, 671, 394+ 926, 927, 254, 255};395+#endif 396+ 397+#if defined(DEC_DPD2BIN) && DEC_DPD2BIN==1 && !defined(DECDPD2BIN)398+#define DECDPD2BIN399+ 400+const uint16_t DPD2BIN[1024]={ 0, 1, 2, 3, 4, 5, 6, 7, 401+ 8, 9, 80, 81, 800, 801, 880, 881, 10, 11, 12, 13, 14, 402+ 15, 16, 17, 18, 19, 90, 91, 810, 811, 890, 891, 20, 21, 403+ 22, 23, 24, 25, 26, 27, 28, 29, 82, 83, 820, 821, 808, 404+ 809, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 92, 93, 405+ 830, 831, 818, 819, 40, 41, 42, 43, 44, 45, 46, 47, 48, 406+ 49, 84, 85, 840, 841, 88, 89, 50, 51, 52, 53, 54, 55, 407+ 56, 57, 58, 59, 94, 95, 850, 851, 98, 99, 60, 61, 62, 408+ 63, 64, 65, 66, 67, 68, 69, 86, 87, 860, 861, 888, 889, 409+ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 96, 97, 870, 410+ 871, 898, 899, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 411+ 180, 181, 900, 901, 980, 981, 110, 111, 112, 113, 114, 115, 116, 412+ 117, 118, 119, 190, 191, 910, 911, 990, 991, 120, 121, 122, 123, 413+ 124, 125, 126, 127, 128, 129, 182, 183, 920, 921, 908, 909, 130, 414+ 131, 132, 133, 134, 135, 136, 137, 138, 139, 192, 193, 930, 931, 415+ 918, 919, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 184, 416+ 185, 940, 941, 188, 189, 150, 151, 152, 153, 154, 155, 156, 157, 417+ 158, 159, 194, 195, 950, 951, 198, 199, 160, 161, 162, 163, 164, 418+ 165, 166, 167, 168, 169, 186, 187, 960, 961, 988, 989, 170, 171, 419+ 172, 173, 174, 175, 176, 177, 178, 179, 196, 197, 970, 971, 998, 420+ 999, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 280, 281, 421+ 802, 803, 882, 883, 210, 211, 212, 213, 214, 215, 216, 217, 218, 422+ 219, 290, 291, 812, 813, 892, 893, 220, 221, 222, 223, 224, 225, 423+ 226, 227, 228, 229, 282, 283, 822, 823, 828, 829, 230, 231, 232, 424+ 233, 234, 235, 236, 237, 238, 239, 292, 293, 832, 833, 838, 839, 425+ 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 284, 285, 842, 426+ 843, 288, 289, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 427+ 294, 295, 852, 853, 298, 299, 260, 261, 262, 263, 264, 265, 266, 428+ 267, 268, 269, 286, 287, 862, 863, 888, 889, 270, 271, 272, 273, 429+ 274, 275, 276, 277, 278, 279, 296, 297, 872, 873, 898, 899, 300, 430+ 301, 302, 303, 304, 305, 306, 307, 308, 309, 380, 381, 902, 903, 431+ 982, 983, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 390, 432+ 391, 912, 913, 992, 993, 320, 321, 322, 323, 324, 325, 326, 327, 433+ 328, 329, 382, 383, 922, 923, 928, 929, 330, 331, 332, 333, 334, 434+ 335, 336, 337, 338, 339, 392, 393, 932, 933, 938, 939, 340, 341, 435+ 342, 343, 344, 345, 346, 347, 348, 349, 384, 385, 942, 943, 388, 436+ 389, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 394, 395, 437+ 952, 953, 398, 399, 360, 361, 362, 363, 364, 365, 366, 367, 368, 438+ 369, 386, 387, 962, 963, 988, 989, 370, 371, 372, 373, 374, 375, 439+ 376, 377, 378, 379, 396, 397, 972, 973, 998, 999, 400, 401, 402, 440+ 403, 404, 405, 406, 407, 408, 409, 480, 481, 804, 805, 884, 885, 441+ 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 490, 491, 814, 442+ 815, 894, 895, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 443+ 482, 483, 824, 825, 848, 849, 430, 431, 432, 433, 434, 435, 436, 444+ 437, 438, 439, 492, 493, 834, 835, 858, 859, 440, 441, 442, 443, 445+ 444, 445, 446, 447, 448, 449, 484, 485, 844, 845, 488, 489, 450, 446+ 451, 452, 453, 454, 455, 456, 457, 458, 459, 494, 495, 854, 855, 447+ 498, 499, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 486, 448+ 487, 864, 865, 888, 889, 470, 471, 472, 473, 474, 475, 476, 477, 449+ 478, 479, 496, 497, 874, 875, 898, 899, 500, 501, 502, 503, 504, 450+ 505, 506, 507, 508, 509, 580, 581, 904, 905, 984, 985, 510, 511, 451+ 512, 513, 514, 515, 516, 517, 518, 519, 590, 591, 914, 915, 994, 452+ 995, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 582, 583, 453+ 924, 925, 948, 949, 530, 531, 532, 533, 534, 535, 536, 537, 538, 454+ 539, 592, 593, 934, 935, 958, 959, 540, 541, 542, 543, 544, 545, 455+ 546, 547, 548, 549, 584, 585, 944, 945, 588, 589, 550, 551, 552, 456+ 553, 554, 555, 556, 557, 558, 559, 594, 595, 954, 955, 598, 599, 457+ 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 586, 587, 964, 458+ 965, 988, 989, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 459+ 596, 597, 974, 975, 998, 999, 600, 601, 602, 603, 604, 605, 606, 460+ 607, 608, 609, 680, 681, 806, 807, 886, 887, 610, 611, 612, 613, 461+ 614, 615, 616, 617, 618, 619, 690, 691, 816, 817, 896, 897, 620, 462+ 621, 622, 623, 624, 625, 626, 627, 628, 629, 682, 683, 826, 827, 463+ 868, 869, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 692, 464+ 693, 836, 837, 878, 879, 640, 641, 642, 643, 644, 645, 646, 647, 465+ 648, 649, 684, 685, 846, 847, 688, 689, 650, 651, 652, 653, 654, 466+ 655, 656, 657, 658, 659, 694, 695, 856, 857, 698, 699, 660, 661, 467+ 662, 663, 664, 665, 666, 667, 668, 669, 686, 687, 866, 867, 888, 468+ 889, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 696, 697, 469+ 876, 877, 898, 899, 700, 701, 702, 703, 704, 705, 706, 707, 708, 470+ 709, 780, 781, 906, 907, 986, 987, 710, 711, 712, 713, 714, 715, 471+ 716, 717, 718, 719, 790, 791, 916, 917, 996, 997, 720, 721, 722, 472+ 723, 724, 725, 726, 727, 728, 729, 782, 783, 926, 927, 968, 969, 473+ 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 792, 793, 936, 474+ 937, 978, 979, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 475+ 784, 785, 946, 947, 788, 789, 750, 751, 752, 753, 754, 755, 756, 476+ 757, 758, 759, 794, 795, 956, 957, 798, 799, 760, 761, 762, 763, 477+ 764, 765, 766, 767, 768, 769, 786, 787, 966, 967, 988, 989, 770, 478+ 771, 772, 773, 774, 775, 776, 777, 778, 779, 796, 797, 976, 977, 479+ 998, 999};480+#endif481+ 482+#if defined(DEC_DPD2BINK) && DEC_DPD2BINK==1 && !defined(DECDPD2BINK)483+#define DECDPD2BINK484+ 485+const uint32_t DPD2BINK[1024]={ 0, 1000, 2000, 3000, 4000, 5000, 486+ 6000, 7000, 8000, 9000, 80000, 81000, 800000, 801000, 880000, 881000, 487+ 10000, 11000, 12000, 13000, 14000, 15000, 16000, 17000, 18000, 19000, 488+ 90000, 91000, 810000, 811000, 890000, 891000, 20000, 21000, 22000, 23000, 489+ 24000, 25000, 26000, 27000, 28000, 29000, 82000, 83000, 820000, 821000, 490+ 808000, 809000, 30000, 31000, 32000, 33000, 34000, 35000, 36000, 37000, 491+ 38000, 39000, 92000, 93000, 830000, 831000, 818000, 819000, 40000, 41000, 492+ 42000, 43000, 44000, 45000, 46000, 47000, 48000, 49000, 84000, 85000, 493+ 840000, 841000, 88000, 89000, 50000, 51000, 52000, 53000, 54000, 55000, 494+ 56000, 57000, 58000, 59000, 94000, 95000, 850000, 851000, 98000, 99000, 495+ 60000, 61000, 62000, 63000, 64000, 65000, 66000, 67000, 68000, 69000, 496+ 86000, 87000, 860000, 861000, 888000, 889000, 70000, 71000, 72000, 73000, 497+ 74000, 75000, 76000, 77000, 78000, 79000, 96000, 97000, 870000, 871000, 498+ 898000, 899000, 100000, 101000, 102000, 103000, 104000, 105000, 106000, 107000, 499+ 108000, 109000, 180000, 181000, 900000, 901000, 980000, 981000, 110000, 111000, 500+ 112000, 113000, 114000, 115000, 116000, 117000, 118000, 119000, 190000, 191000, 501+ 910000, 911000, 990000, 991000, 120000, 121000, 122000, 123000, 124000, 125000, 502+ 126000, 127000, 128000, 129000, 182000, 183000, 920000, 921000, 908000, 909000, 503+ 130000, 131000, 132000, 133000, 134000, 135000, 136000, 137000, 138000, 139000, 504+ 192000, 193000, 930000, 931000, 918000, 919000, 140000, 141000, 142000, 143000, 505+ 144000, 145000, 146000, 147000, 148000, 149000, 184000, 185000, 940000, 941000, 506+ 188000, 189000, 150000, 151000, 152000, 153000, 154000, 155000, 156000, 157000, 507+ 158000, 159000, 194000, 195000, 950000, 951000, 198000, 199000, 160000, 161000, 508+ 162000, 163000, 164000, 165000, 166000, 167000, 168000, 169000, 186000, 187000, 509+ 960000, 961000, 988000, 989000, 170000, 171000, 172000, 173000, 174000, 175000, 510+ 176000, 177000, 178000, 179000, 196000, 197000, 970000, 971000, 998000, 999000, 511+ 200000, 201000, 202000, 203000, 204000, 205000, 206000, 207000, 208000, 209000, 512+ 280000, 281000, 802000, 803000, 882000, 883000, 210000, 211000, 212000, 213000, 513+ 214000, 215000, 216000, 217000, 218000, 219000, 290000, 291000, 812000, 813000, 514+ 892000, 893000, 220000, 221000, 222000, 223000, 224000, 225000, 226000, 227000, 515+ 228000, 229000, 282000, 283000, 822000, 823000, 828000, 829000, 230000, 231000, 516+ 232000, 233000, 234000, 235000, 236000, 237000, 238000, 239000, 292000, 293000, 517+ 832000, 833000, 838000, 839000, 240000, 241000, 242000, 243000, 244000, 245000, 518+ 246000, 247000, 248000, 249000, 284000, 285000, 842000, 843000, 288000, 289000, 519+ 250000, 251000, 252000, 253000, 254000, 255000, 256000, 257000, 258000, 259000, 520+ 294000, 295000, 852000, 853000, 298000, 299000, 260000, 261000, 262000, 263000, 521+ 264000, 265000, 266000, 267000, 268000, 269000, 286000, 287000, 862000, 863000, 522+ 888000, 889000, 270000, 271000, 272000, 273000, 274000, 275000, 276000, 277000, 523+ 278000, 279000, 296000, 297000, 872000, 873000, 898000, 899000, 300000, 301000, 524+ 302000, 303000, 304000, 305000, 306000, 307000, 308000, 309000, 380000, 381000, 525+ 902000, 903000, 982000, 983000, 310000, 311000, 312000, 313000, 314000, 315000, 526+ 316000, 317000, 318000, 319000, 390000, 391000, 912000, 913000, 992000, 993000, 527+ 320000, 321000, 322000, 323000, 324000, 325000, 326000, 327000, 328000, 329000, 528+ 382000, 383000, 922000, 923000, 928000, 929000, 330000, 331000, 332000, 333000, 529+ 334000, 335000, 336000, 337000, 338000, 339000, 392000, 393000, 932000, 933000, 530+ 938000, 939000, 340000, 341000, 342000, 343000, 344000, 345000, 346000, 347000, 531+ 348000, 349000, 384000, 385000, 942000, 943000, 388000, 389000, 350000, 351000, 532+ 352000, 353000, 354000, 355000, 356000, 357000, 358000, 359000, 394000, 395000, 533+ 952000, 953000, 398000, 399000, 360000, 361000, 362000, 363000, 364000, 365000, 534+ 366000, 367000, 368000, 369000, 386000, 387000, 962000, 963000, 988000, 989000, 535+ 370000, 371000, 372000, 373000, 374000, 375000, 376000, 377000, 378000, 379000, 536+ 396000, 397000, 972000, 973000, 998000, 999000, 400000, 401000, 402000, 403000, 537+ 404000, 405000, 406000, 407000, 408000, 409000, 480000, 481000, 804000, 805000, 538+ 884000, 885000, 410000, 411000, 412000, 413000, 414000, 415000, 416000, 417000, 539+ 418000, 419000, 490000, 491000, 814000, 815000, 894000, 895000, 420000, 421000, 540+ 422000, 423000, 424000, 425000, 426000, 427000, 428000, 429000, 482000, 483000, 541+ 824000, 825000, 848000, 849000, 430000, 431000, 432000, 433000, 434000, 435000, 542+ 436000, 437000, 438000, 439000, 492000, 493000, 834000, 835000, 858000, 859000, 543+ 440000, 441000, 442000, 443000, 444000, 445000, 446000, 447000, 448000, 449000, 544+ 484000, 485000, 844000, 845000, 488000, 489000, 450000, 451000, 452000, 453000, 545+ 454000, 455000, 456000, 457000, 458000, 459000, 494000, 495000, 854000, 855000, 546+ 498000, 499000, 460000, 461000, 462000, 463000, 464000, 465000, 466000, 467000, 547+ 468000, 469000, 486000, 487000, 864000, 865000, 888000, 889000, 470000, 471000, 548+ 472000, 473000, 474000, 475000, 476000, 477000, 478000, 479000, 496000, 497000, 549+ 874000, 875000, 898000, 899000, 500000, 501000, 502000, 503000, 504000, 505000, 550+ 506000, 507000, 508000, 509000, 580000, 581000, 904000, 905000, 984000, 985000, 551+ 510000, 511000, 512000, 513000, 514000, 515000, 516000, 517000, 518000, 519000, 552+ 590000, 591000, 914000, 915000, 994000, 995000, 520000, 521000, 522000, 523000, 553+ 524000, 525000, 526000, 527000, 528000, 529000, 582000, 583000, 924000, 925000, 554+ 948000, 949000, 530000, 531000, 532000, 533000, 534000, 535000, 536000, 537000, 555+ 538000, 539000, 592000, 593000, 934000, 935000, 958000, 959000, 540000, 541000, 556+ 542000, 543000, 544000, 545000, 546000, 547000, 548000, 549000, 584000, 585000, 557+ 944000, 945000, 588000, 589000, 550000, 551000, 552000, 553000, 554000, 555000, 558+ 556000, 557000, 558000, 559000, 594000, 595000, 954000, 955000, 598000, 599000, 559+ 560000, 561000, 562000, 563000, 564000, 565000, 566000, 567000, 568000, 569000, 560+ 586000, 587000, 964000, 965000, 988000, 989000, 570000, 571000, 572000, 573000, 561+ 574000, 575000, 576000, 577000, 578000, 579000, 596000, 597000, 974000, 975000, 562+ 998000, 999000, 600000, 601000, 602000, 603000, 604000, 605000, 606000, 607000, 563+ 608000, 609000, 680000, 681000, 806000, 807000, 886000, 887000, 610000, 611000, 564+ 612000, 613000, 614000, 615000, 616000, 617000, 618000, 619000, 690000, 691000, 565+ 816000, 817000, 896000, 897000, 620000, 621000, 622000, 623000, 624000, 625000, 566+ 626000, 627000, 628000, 629000, 682000, 683000, 826000, 827000, 868000, 869000, 567+ 630000, 631000, 632000, 633000, 634000, 635000, 636000, 637000, 638000, 639000, 568+ 692000, 693000, 836000, 837000, 878000, 879000, 640000, 641000, 642000, 643000, 569+ 644000, 645000, 646000, 647000, 648000, 649000, 684000, 685000, 846000, 847000, 570+ 688000, 689000, 650000, 651000, 652000, 653000, 654000, 655000, 656000, 657000, 571+ 658000, 659000, 694000, 695000, 856000, 857000, 698000, 699000, 660000, 661000, 572+ 662000, 663000, 664000, 665000, 666000, 667000, 668000, 669000, 686000, 687000, 573+ 866000, 867000, 888000, 889000, 670000, 671000, 672000, 673000, 674000, 675000, 574+ 676000, 677000, 678000, 679000, 696000, 697000, 876000, 877000, 898000, 899000, 575+ 700000, 701000, 702000, 703000, 704000, 705000, 706000, 707000, 708000, 709000, 576+ 780000, 781000, 906000, 907000, 986000, 987000, 710000, 711000, 712000, 713000, 577+ 714000, 715000, 716000, 717000, 718000, 719000, 790000, 791000, 916000, 917000, 578+ 996000, 997000, 720000, 721000, 722000, 723000, 724000, 725000, 726000, 727000, 579+ 728000, 729000, 782000, 783000, 926000, 927000, 968000, 969000, 730000, 731000, 580+ 732000, 733000, 734000, 735000, 736000, 737000, 738000, 739000, 792000, 793000, 581+ 936000, 937000, 978000, 979000, 740000, 741000, 742000, 743000, 744000, 745000, 582+ 746000, 747000, 748000, 749000, 784000, 785000, 946000, 947000, 788000, 789000, 583+ 750000, 751000, 752000, 753000, 754000, 755000, 756000, 757000, 758000, 759000, 584+ 794000, 795000, 956000, 957000, 798000, 799000, 760000, 761000, 762000, 763000, 585+ 764000, 765000, 766000, 767000, 768000, 769000, 786000, 787000, 966000, 967000, 586+ 988000, 989000, 770000, 771000, 772000, 773000, 774000, 775000, 776000, 777000, 587+ 778000, 779000, 796000, 797000, 976000, 977000, 998000, 999000};588+#endif589+ 590+#if defined(DEC_DPD2BINM) && DEC_DPD2BINM==1 && !defined(DECDPD2BINM)591+#define DECDPD2BINM592+ 593+const uint32_t DPD2BINM[1024]={0, 1000000, 2000000, 3000000, 4000000, 594+ 5000000, 6000000, 7000000, 8000000, 9000000, 80000000, 81000000, 595+ 800000000, 801000000, 880000000, 881000000, 10000000, 11000000, 12000000, 596+ 13000000, 14000000, 15000000, 16000000, 17000000, 18000000, 19000000, 597+ 90000000, 91000000, 810000000, 811000000, 890000000, 891000000, 20000000, 598+ 21000000, 22000000, 23000000, 24000000, 25000000, 26000000, 27000000, 599+ 28000000, 29000000, 82000000, 83000000, 820000000, 821000000, 808000000, 600+ 809000000, 30000000, 31000000, 32000000, 33000000, 34000000, 35000000, 601+ 36000000, 37000000, 38000000, 39000000, 92000000, 93000000, 830000000, 602+ 831000000, 818000000, 819000000, 40000000, 41000000, 42000000, 43000000, 603+ 44000000, 45000000, 46000000, 47000000, 48000000, 49000000, 84000000, 604+ 85000000, 840000000, 841000000, 88000000, 89000000, 50000000, 51000000, 605+ 52000000, 53000000, 54000000, 55000000, 56000000, 57000000, 58000000, 606+ 59000000, 94000000, 95000000, 850000000, 851000000, 98000000, 99000000, 607+ 60000000, 61000000, 62000000, 63000000, 64000000, 65000000, 66000000, 608+ 67000000, 68000000, 69000000, 86000000, 87000000, 860000000, 861000000, 609+ 888000000, 889000000, 70000000, 71000000, 72000000, 73000000, 74000000, 610+ 75000000, 76000000, 77000000, 78000000, 79000000, 96000000, 97000000, 611+ 870000000, 871000000, 898000000, 899000000, 100000000, 101000000, 102000000, 612+ 103000000, 104000000, 105000000, 106000000, 107000000, 108000000, 109000000, 613+ 180000000, 181000000, 900000000, 901000000, 980000000, 981000000, 110000000, 614+ 111000000, 112000000, 113000000, 114000000, 115000000, 116000000, 117000000, 615+ 118000000, 119000000, 190000000, 191000000, 910000000, 911000000, 990000000, 616+ 991000000, 120000000, 121000000, 122000000, 123000000, 124000000, 125000000, 617+ 126000000, 127000000, 128000000, 129000000, 182000000, 183000000, 920000000, 618+ 921000000, 908000000, 909000000, 130000000, 131000000, 132000000, 133000000, 619+ 134000000, 135000000, 136000000, 137000000, 138000000, 139000000, 192000000, 620+ 193000000, 930000000, 931000000, 918000000, 919000000, 140000000, 141000000, 621+ 142000000, 143000000, 144000000, 145000000, 146000000, 147000000, 148000000, 622+ 149000000, 184000000, 185000000, 940000000, 941000000, 188000000, 189000000, 623+ 150000000, 151000000, 152000000, 153000000, 154000000, 155000000, 156000000, 624+ 157000000, 158000000, 159000000, 194000000, 195000000, 950000000, 951000000, 625+ 198000000, 199000000, 160000000, 161000000, 162000000, 163000000, 164000000, 626+ 165000000, 166000000, 167000000, 168000000, 169000000, 186000000, 187000000, 627+ 960000000, 961000000, 988000000, 989000000, 170000000, 171000000, 172000000, 628+ 173000000, 174000000, 175000000, 176000000, 177000000, 178000000, 179000000, 629+ 196000000, 197000000, 970000000, 971000000, 998000000, 999000000, 200000000, 630+ 201000000, 202000000, 203000000, 204000000, 205000000, 206000000, 207000000, 631+ 208000000, 209000000, 280000000, 281000000, 802000000, 803000000, 882000000, 632+ 883000000, 210000000, 211000000, 212000000, 213000000, 214000000, 215000000, 633+ 216000000, 217000000, 218000000, 219000000, 290000000, 291000000, 812000000, 634+ 813000000, 892000000, 893000000, 220000000, 221000000, 222000000, 223000000, 635+ 224000000, 225000000, 226000000, 227000000, 228000000, 229000000, 282000000, 636+ 283000000, 822000000, 823000000, 828000000, 829000000, 230000000, 231000000, 637+ 232000000, 233000000, 234000000, 235000000, 236000000, 237000000, 238000000, 638+ 239000000, 292000000, 293000000, 832000000, 833000000, 838000000, 839000000, 639+ 240000000, 241000000, 242000000, 243000000, 244000000, 245000000, 246000000, 640+ 247000000, 248000000, 249000000, 284000000, 285000000, 842000000, 843000000, 641+ 288000000, 289000000, 250000000, 251000000, 252000000, 253000000, 254000000, 642+ 255000000, 256000000, 257000000, 258000000, 259000000, 294000000, 295000000, 643+ 852000000, 853000000, 298000000, 299000000, 260000000, 261000000, 262000000, 644+ 263000000, 264000000, 265000000, 266000000, 267000000, 268000000, 269000000, 645+ 286000000, 287000000, 862000000, 863000000, 888000000, 889000000, 270000000, 646+ 271000000, 272000000, 273000000, 274000000, 275000000, 276000000, 277000000, 647+ 278000000, 279000000, 296000000, 297000000, 872000000, 873000000, 898000000, 648+ 899000000, 300000000, 301000000, 302000000, 303000000, 304000000, 305000000, 649+ 306000000, 307000000, 308000000, 309000000, 380000000, 381000000, 902000000, 650+ 903000000, 982000000, 983000000, 310000000, 311000000, 312000000, 313000000, 651+ 314000000, 315000000, 316000000, 317000000, 318000000, 319000000, 390000000, 652+ 391000000, 912000000, 913000000, 992000000, 993000000, 320000000, 321000000, 653+ 322000000, 323000000, 324000000, 325000000, 326000000, 327000000, 328000000, 654+ 329000000, 382000000, 383000000, 922000000, 923000000, 928000000, 929000000, 655+ 330000000, 331000000, 332000000, 333000000, 334000000, 335000000, 336000000, 656+ 337000000, 338000000, 339000000, 392000000, 393000000, 932000000, 933000000, 657+ 938000000, 939000000, 340000000, 341000000, 342000000, 343000000, 344000000, 658+ 345000000, 346000000, 347000000, 348000000, 349000000, 384000000, 385000000, 659+ 942000000, 943000000, 388000000, 389000000, 350000000, 351000000, 352000000, 660+ 353000000, 354000000, 355000000, 356000000, 357000000, 358000000, 359000000, 661+ 394000000, 395000000, 952000000, 953000000, 398000000, 399000000, 360000000, 662+ 361000000, 362000000, 363000000, 364000000, 365000000, 366000000, 367000000, 663+ 368000000, 369000000, 386000000, 387000000, 962000000, 963000000, 988000000, 664+ 989000000, 370000000, 371000000, 372000000, 373000000, 374000000, 375000000, 665+ 376000000, 377000000, 378000000, 379000000, 396000000, 397000000, 972000000, 666+ 973000000, 998000000, 999000000, 400000000, 401000000, 402000000, 403000000, 667+ 404000000, 405000000, 406000000, 407000000, 408000000, 409000000, 480000000, 668+ 481000000, 804000000, 805000000, 884000000, 885000000, 410000000, 411000000, 669+ 412000000, 413000000, 414000000, 415000000, 416000000, 417000000, 418000000, 670+ 419000000, 490000000, 491000000, 814000000, 815000000, 894000000, 895000000, 671+ 420000000, 421000000, 422000000, 423000000, 424000000, 425000000, 426000000, 672+ 427000000, 428000000, 429000000, 482000000, 483000000, 824000000, 825000000, 673+ 848000000, 849000000, 430000000, 431000000, 432000000, 433000000, 434000000, 674+ 435000000, 436000000, 437000000, 438000000, 439000000, 492000000, 493000000, 675+ 834000000, 835000000, 858000000, 859000000, 440000000, 441000000, 442000000, 676+ 443000000, 444000000, 445000000, 446000000, 447000000, 448000000, 449000000, 677+ 484000000, 485000000, 844000000, 845000000, 488000000, 489000000, 450000000, 678+ 451000000, 452000000, 453000000, 454000000, 455000000, 456000000, 457000000, 679+ 458000000, 459000000, 494000000, 495000000, 854000000, 855000000, 498000000, 680+ 499000000, 460000000, 461000000, 462000000, 463000000, 464000000, 465000000, 681+ 466000000, 467000000, 468000000, 469000000, 486000000, 487000000, 864000000, 682+ 865000000, 888000000, 889000000, 470000000, 471000000, 472000000, 473000000, 683+ 474000000, 475000000, 476000000, 477000000, 478000000, 479000000, 496000000, 684+ 497000000, 874000000, 875000000, 898000000, 899000000, 500000000, 501000000, 685+ 502000000, 503000000, 504000000, 505000000, 506000000, 507000000, 508000000, 686+ 509000000, 580000000, 581000000, 904000000, 905000000, 984000000, 985000000, 687+ 510000000, 511000000, 512000000, 513000000, 514000000, 515000000, 516000000, 688+ 517000000, 518000000, 519000000, 590000000, 591000000, 914000000, 915000000, 689+ 994000000, 995000000, 520000000, 521000000, 522000000, 523000000, 524000000, 690+ 525000000, 526000000, 527000000, 528000000, 529000000, 582000000, 583000000, 691+ 924000000, 925000000, 948000000, 949000000, 530000000, 531000000, 532000000, 692+ 533000000, 534000000, 535000000, 536000000, 537000000, 538000000, 539000000, 693+ 592000000, 593000000, 934000000, 935000000, 958000000, 959000000, 540000000, 694+ 541000000, 542000000, 543000000, 544000000, 545000000, 546000000, 547000000, 695+ 548000000, 549000000, 584000000, 585000000, 944000000, 945000000, 588000000, 696+ 589000000, 550000000, 551000000, 552000000, 553000000, 554000000, 555000000, 697+ 556000000, 557000000, 558000000, 559000000, 594000000, 595000000, 954000000, 698+ 955000000, 598000000, 599000000, 560000000, 561000000, 562000000, 563000000, 699+ 564000000, 565000000, 566000000, 567000000, 568000000, 569000000, 586000000, 700+ 587000000, 964000000, 965000000, 988000000, 989000000, 570000000, 571000000, 701+ 572000000, 573000000, 574000000, 575000000, 576000000, 577000000, 578000000, 702+ 579000000, 596000000, 597000000, 974000000, 975000000, 998000000, 999000000, 703+ 600000000, 601000000, 602000000, 603000000, 604000000, 605000000, 606000000, 704+ 607000000, 608000000, 609000000, 680000000, 681000000, 806000000, 807000000, 705+ 886000000, 887000000, 610000000, 611000000, 612000000, 613000000, 614000000, 706+ 615000000, 616000000, 617000000, 618000000, 619000000, 690000000, 691000000, 707+ 816000000, 817000000, 896000000, 897000000, 620000000, 621000000, 622000000, 708+ 623000000, 624000000, 625000000, 626000000, 627000000, 628000000, 629000000, 709+ 682000000, 683000000, 826000000, 827000000, 868000000, 869000000, 630000000, 710+ 631000000, 632000000, 633000000, 634000000, 635000000, 636000000, 637000000, 711+ 638000000, 639000000, 692000000, 693000000, 836000000, 837000000, 878000000, 712+ 879000000, 640000000, 641000000, 642000000, 643000000, 644000000, 645000000, 713+ 646000000, 647000000, 648000000, 649000000, 684000000, 685000000, 846000000, 714+ 847000000, 688000000, 689000000, 650000000, 651000000, 652000000, 653000000, 715+ 654000000, 655000000, 656000000, 657000000, 658000000, 659000000, 694000000, 716+ 695000000, 856000000, 857000000, 698000000, 699000000, 660000000, 661000000, 717+ 662000000, 663000000, 664000000, 665000000, 666000000, 667000000, 668000000, 718+ 669000000, 686000000, 687000000, 866000000, 867000000, 888000000, 889000000, 719+ 670000000, 671000000, 672000000, 673000000, 674000000, 675000000, 676000000, 720+ 677000000, 678000000, 679000000, 696000000, 697000000, 876000000, 877000000, 721+ 898000000, 899000000, 700000000, 701000000, 702000000, 703000000, 704000000, 722+ 705000000, 706000000, 707000000, 708000000, 709000000, 780000000, 781000000, 723+ 906000000, 907000000, 986000000, 987000000, 710000000, 711000000, 712000000, 724+ 713000000, 714000000, 715000000, 716000000, 717000000, 718000000, 719000000, 725+ 790000000, 791000000, 916000000, 917000000, 996000000, 997000000, 720000000, 726+ 721000000, 722000000, 723000000, 724000000, 725000000, 726000000, 727000000, 727+ 728000000, 729000000, 782000000, 783000000, 926000000, 927000000, 968000000, 728+ 969000000, 730000000, 731000000, 732000000, 733000000, 734000000, 735000000, 729+ 736000000, 737000000, 738000000, 739000000, 792000000, 793000000, 936000000, 730+ 937000000, 978000000, 979000000, 740000000, 741000000, 742000000, 743000000, 731+ 744000000, 745000000, 746000000, 747000000, 748000000, 749000000, 784000000, 732+ 785000000, 946000000, 947000000, 788000000, 789000000, 750000000, 751000000, 733+ 752000000, 753000000, 754000000, 755000000, 756000000, 757000000, 758000000, 734+ 759000000, 794000000, 795000000, 956000000, 957000000, 798000000, 799000000, 735+ 760000000, 761000000, 762000000, 763000000, 764000000, 765000000, 766000000, 736+ 767000000, 768000000, 769000000, 786000000, 787000000, 966000000, 967000000, 737+ 988000000, 989000000, 770000000, 771000000, 772000000, 773000000, 774000000, 738+ 775000000, 776000000, 777000000, 778000000, 779000000, 796000000, 797000000, 739+ 976000000, 977000000, 998000000, 999000000};740+#endif741+ 742+#if defined(DEC_BIN2CHAR) && DEC_BIN2CHAR==1 && !defined(DECBIN2CHAR)743+#define DECBIN2CHAR744+ 745+const uint8_t BIN2CHAR[4001]={746+ '\0','0','0','0', '\1','0','0','1', '\1','0','0','2', '\1','0','0','3', '\1','0','0','4', 747+ '\1','0','0','5', '\1','0','0','6', '\1','0','0','7', '\1','0','0','8', '\1','0','0','9', 748+ '\2','0','1','0', '\2','0','1','1', '\2','0','1','2', '\2','0','1','3', '\2','0','1','4', 749+ '\2','0','1','5', '\2','0','1','6', '\2','0','1','7', '\2','0','1','8', '\2','0','1','9', 750+ '\2','0','2','0', '\2','0','2','1', '\2','0','2','2', '\2','0','2','3', '\2','0','2','4', 751+ '\2','0','2','5', '\2','0','2','6', '\2','0','2','7', '\2','0','2','8', '\2','0','2','9', 752+ '\2','0','3','0', '\2','0','3','1', '\2','0','3','2', '\2','0','3','3', '\2','0','3','4', 753+ '\2','0','3','5', '\2','0','3','6', '\2','0','3','7', '\2','0','3','8', '\2','0','3','9', 754+ '\2','0','4','0', '\2','0','4','1', '\2','0','4','2', '\2','0','4','3', '\2','0','4','4', 755+ '\2','0','4','5', '\2','0','4','6', '\2','0','4','7', '\2','0','4','8', '\2','0','4','9', 756+ '\2','0','5','0', '\2','0','5','1', '\2','0','5','2', '\2','0','5','3', '\2','0','5','4', 757+ '\2','0','5','5', '\2','0','5','6', '\2','0','5','7', '\2','0','5','8', '\2','0','5','9', 758+ '\2','0','6','0', '\2','0','6','1', '\2','0','6','2', '\2','0','6','3', '\2','0','6','4', 759+ '\2','0','6','5', '\2','0','6','6', '\2','0','6','7', '\2','0','6','8', '\2','0','6','9', 760+ '\2','0','7','0', '\2','0','7','1', '\2','0','7','2', '\2','0','7','3', '\2','0','7','4', 761+ '\2','0','7','5', '\2','0','7','6', '\2','0','7','7', '\2','0','7','8', '\2','0','7','9', 762+ '\2','0','8','0', '\2','0','8','1', '\2','0','8','2', '\2','0','8','3', '\2','0','8','4', 763+ '\2','0','8','5', '\2','0','8','6', '\2','0','8','7', '\2','0','8','8', '\2','0','8','9', 764+ '\2','0','9','0', '\2','0','9','1', '\2','0','9','2', '\2','0','9','3', '\2','0','9','4', 765+ '\2','0','9','5', '\2','0','9','6', '\2','0','9','7', '\2','0','9','8', '\2','0','9','9', 766+ '\3','1','0','0', '\3','1','0','1', '\3','1','0','2', '\3','1','0','3', '\3','1','0','4', 767+ '\3','1','0','5', '\3','1','0','6', '\3','1','0','7', '\3','1','0','8', '\3','1','0','9', 768+ '\3','1','1','0', '\3','1','1','1', '\3','1','1','2', '\3','1','1','3', '\3','1','1','4', 769+ '\3','1','1','5', '\3','1','1','6', '\3','1','1','7', '\3','1','1','8', '\3','1','1','9', 770+ '\3','1','2','0', '\3','1','2','1', '\3','1','2','2', '\3','1','2','3', '\3','1','2','4', 771+ '\3','1','2','5', '\3','1','2','6', '\3','1','2','7', '\3','1','2','8', '\3','1','2','9', 772+ '\3','1','3','0', '\3','1','3','1', '\3','1','3','2', '\3','1','3','3', '\3','1','3','4', 773+ '\3','1','3','5', '\3','1','3','6', '\3','1','3','7', '\3','1','3','8', '\3','1','3','9', 774+ '\3','1','4','0', '\3','1','4','1', '\3','1','4','2', '\3','1','4','3', '\3','1','4','4', 775+ '\3','1','4','5', '\3','1','4','6', '\3','1','4','7', '\3','1','4','8', '\3','1','4','9', 776+ '\3','1','5','0', '\3','1','5','1', '\3','1','5','2', '\3','1','5','3', '\3','1','5','4', 777+ '\3','1','5','5', '\3','1','5','6', '\3','1','5','7', '\3','1','5','8', '\3','1','5','9', 778+ '\3','1','6','0', '\3','1','6','1', '\3','1','6','2', '\3','1','6','3', '\3','1','6','4', 779+ '\3','1','6','5', '\3','1','6','6', '\3','1','6','7', '\3','1','6','8', '\3','1','6','9', 780+ '\3','1','7','0', '\3','1','7','1', '\3','1','7','2', '\3','1','7','3', '\3','1','7','4', 781+ '\3','1','7','5', '\3','1','7','6', '\3','1','7','7', '\3','1','7','8', '\3','1','7','9', 782+ '\3','1','8','0', '\3','1','8','1', '\3','1','8','2', '\3','1','8','3', '\3','1','8','4', 783+ '\3','1','8','5', '\3','1','8','6', '\3','1','8','7', '\3','1','8','8', '\3','1','8','9', 784+ '\3','1','9','0', '\3','1','9','1', '\3','1','9','2', '\3','1','9','3', '\3','1','9','4', 785+ '\3','1','9','5', '\3','1','9','6', '\3','1','9','7', '\3','1','9','8', '\3','1','9','9', 786+ '\3','2','0','0', '\3','2','0','1', '\3','2','0','2', '\3','2','0','3', '\3','2','0','4', 787+ '\3','2','0','5', '\3','2','0','6', '\3','2','0','7', '\3','2','0','8', '\3','2','0','9', 788+ '\3','2','1','0', '\3','2','1','1', '\3','2','1','2', '\3','2','1','3', '\3','2','1','4', 789+ '\3','2','1','5', '\3','2','1','6', '\3','2','1','7', '\3','2','1','8', '\3','2','1','9', 790+ '\3','2','2','0', '\3','2','2','1', '\3','2','2','2', '\3','2','2','3', '\3','2','2','4', 791+ '\3','2','2','5', '\3','2','2','6', '\3','2','2','7', '\3','2','2','8', '\3','2','2','9', 792+ '\3','2','3','0', '\3','2','3','1', '\3','2','3','2', '\3','2','3','3', '\3','2','3','4', 793+ '\3','2','3','5', '\3','2','3','6', '\3','2','3','7', '\3','2','3','8', '\3','2','3','9', 794+ '\3','2','4','0', '\3','2','4','1', '\3','2','4','2', '\3','2','4','3', '\3','2','4','4', 795+ '\3','2','4','5', '\3','2','4','6', '\3','2','4','7', '\3','2','4','8', '\3','2','4','9', 796+ '\3','2','5','0', '\3','2','5','1', '\3','2','5','2', '\3','2','5','3', '\3','2','5','4', 797+ '\3','2','5','5', '\3','2','5','6', '\3','2','5','7', '\3','2','5','8', '\3','2','5','9', 798+ '\3','2','6','0', '\3','2','6','1', '\3','2','6','2', '\3','2','6','3', '\3','2','6','4', 799+ '\3','2','6','5', '\3','2','6','6', '\3','2','6','7', '\3','2','6','8', '\3','2','6','9', 800+ '\3','2','7','0', '\3','2','7','1', '\3','2','7','2', '\3','2','7','3', '\3','2','7','4', 801+ '\3','2','7','5', '\3','2','7','6', '\3','2','7','7', '\3','2','7','8', '\3','2','7','9', 802+ '\3','2','8','0', '\3','2','8','1', '\3','2','8','2', '\3','2','8','3', '\3','2','8','4', 803+ '\3','2','8','5', '\3','2','8','6', '\3','2','8','7', '\3','2','8','8', '\3','2','8','9', 804+ '\3','2','9','0', '\3','2','9','1', '\3','2','9','2', '\3','2','9','3', '\3','2','9','4', 805+ '\3','2','9','5', '\3','2','9','6', '\3','2','9','7', '\3','2','9','8', '\3','2','9','9', 806+ '\3','3','0','0', '\3','3','0','1', '\3','3','0','2', '\3','3','0','3', '\3','3','0','4', 807+ '\3','3','0','5', '\3','3','0','6', '\3','3','0','7', '\3','3','0','8', '\3','3','0','9', 808+ '\3','3','1','0', '\3','3','1','1', '\3','3','1','2', '\3','3','1','3', '\3','3','1','4', 809+ '\3','3','1','5', '\3','3','1','6', '\3','3','1','7', '\3','3','1','8', '\3','3','1','9', 810+ '\3','3','2','0', '\3','3','2','1', '\3','3','2','2', '\3','3','2','3', '\3','3','2','4', 811+ '\3','3','2','5', '\3','3','2','6', '\3','3','2','7', '\3','3','2','8', '\3','3','2','9', 812+ '\3','3','3','0', '\3','3','3','1', '\3','3','3','2', '\3','3','3','3', '\3','3','3','4', 813+ '\3','3','3','5', '\3','3','3','6', '\3','3','3','7', '\3','3','3','8', '\3','3','3','9', 814+ '\3','3','4','0', '\3','3','4','1', '\3','3','4','2', '\3','3','4','3', '\3','3','4','4', 815+ '\3','3','4','5', '\3','3','4','6', '\3','3','4','7', '\3','3','4','8', '\3','3','4','9', 816+ '\3','3','5','0', '\3','3','5','1', '\3','3','5','2', '\3','3','5','3', '\3','3','5','4', 817+ '\3','3','5','5', '\3','3','5','6', '\3','3','5','7', '\3','3','5','8', '\3','3','5','9', 818+ '\3','3','6','0', '\3','3','6','1', '\3','3','6','2', '\3','3','6','3', '\3','3','6','4', 819+ '\3','3','6','5', '\3','3','6','6', '\3','3','6','7', '\3','3','6','8', '\3','3','6','9', 820+ '\3','3','7','0', '\3','3','7','1', '\3','3','7','2', '\3','3','7','3', '\3','3','7','4', 821+ '\3','3','7','5', '\3','3','7','6', '\3','3','7','7', '\3','3','7','8', '\3','3','7','9', 822+ '\3','3','8','0', '\3','3','8','1', '\3','3','8','2', '\3','3','8','3', '\3','3','8','4', 823+ '\3','3','8','5', '\3','3','8','6', '\3','3','8','7', '\3','3','8','8', '\3','3','8','9', 824+ '\3','3','9','0', '\3','3','9','1', '\3','3','9','2', '\3','3','9','3', '\3','3','9','4', 825+ '\3','3','9','5', '\3','3','9','6', '\3','3','9','7', '\3','3','9','8', '\3','3','9','9', 826+ '\3','4','0','0', '\3','4','0','1', '\3','4','0','2', '\3','4','0','3', '\3','4','0','4', 827+ '\3','4','0','5', '\3','4','0','6', '\3','4','0','7', '\3','4','0','8', '\3','4','0','9', 828+ '\3','4','1','0', '\3','4','1','1', '\3','4','1','2', '\3','4','1','3', '\3','4','1','4', 829+ '\3','4','1','5', '\3','4','1','6', '\3','4','1','7', '\3','4','1','8', '\3','4','1','9', 830+ '\3','4','2','0', '\3','4','2','1', '\3','4','2','2', '\3','4','2','3', '\3','4','2','4', 831+ '\3','4','2','5', '\3','4','2','6', '\3','4','2','7', '\3','4','2','8', '\3','4','2','9', 832+ '\3','4','3','0', '\3','4','3','1', '\3','4','3','2', '\3','4','3','3', '\3','4','3','4', 833+ '\3','4','3','5', '\3','4','3','6', '\3','4','3','7', '\3','4','3','8', '\3','4','3','9', 834+ '\3','4','4','0', '\3','4','4','1', '\3','4','4','2', '\3','4','4','3', '\3','4','4','4', 835+ '\3','4','4','5', '\3','4','4','6', '\3','4','4','7', '\3','4','4','8', '\3','4','4','9', 836+ '\3','4','5','0', '\3','4','5','1', '\3','4','5','2', '\3','4','5','3', '\3','4','5','4', 837+ '\3','4','5','5', '\3','4','5','6', '\3','4','5','7', '\3','4','5','8', '\3','4','5','9', 838+ '\3','4','6','0', '\3','4','6','1', '\3','4','6','2', '\3','4','6','3', '\3','4','6','4', 839+ '\3','4','6','5', '\3','4','6','6', '\3','4','6','7', '\3','4','6','8', '\3','4','6','9', 840+ '\3','4','7','0', '\3','4','7','1', '\3','4','7','2', '\3','4','7','3', '\3','4','7','4', 841+ '\3','4','7','5', '\3','4','7','6', '\3','4','7','7', '\3','4','7','8', '\3','4','7','9', 842+ '\3','4','8','0', '\3','4','8','1', '\3','4','8','2', '\3','4','8','3', '\3','4','8','4', 843+ '\3','4','8','5', '\3','4','8','6', '\3','4','8','7', '\3','4','8','8', '\3','4','8','9', 844+ '\3','4','9','0', '\3','4','9','1', '\3','4','9','2', '\3','4','9','3', '\3','4','9','4', 845+ '\3','4','9','5', '\3','4','9','6', '\3','4','9','7', '\3','4','9','8', '\3','4','9','9', 846+ '\3','5','0','0', '\3','5','0','1', '\3','5','0','2', '\3','5','0','3', '\3','5','0','4', 847+ '\3','5','0','5', '\3','5','0','6', '\3','5','0','7', '\3','5','0','8', '\3','5','0','9', 848+ '\3','5','1','0', '\3','5','1','1', '\3','5','1','2', '\3','5','1','3', '\3','5','1','4', 849+ '\3','5','1','5', '\3','5','1','6', '\3','5','1','7', '\3','5','1','8', '\3','5','1','9', 850+ '\3','5','2','0', '\3','5','2','1', '\3','5','2','2', '\3','5','2','3', '\3','5','2','4', 851+ '\3','5','2','5', '\3','5','2','6', '\3','5','2','7', '\3','5','2','8', '\3','5','2','9', 852+ '\3','5','3','0', '\3','5','3','1', '\3','5','3','2', '\3','5','3','3', '\3','5','3','4', 853+ '\3','5','3','5', '\3','5','3','6', '\3','5','3','7', '\3','5','3','8', '\3','5','3','9', 854+ '\3','5','4','0', '\3','5','4','1', '\3','5','4','2', '\3','5','4','3', '\3','5','4','4', 855+ '\3','5','4','5', '\3','5','4','6', '\3','5','4','7', '\3','5','4','8', '\3','5','4','9', 856+ '\3','5','5','0', '\3','5','5','1', '\3','5','5','2', '\3','5','5','3', '\3','5','5','4', 857+ '\3','5','5','5', '\3','5','5','6', '\3','5','5','7', '\3','5','5','8', '\3','5','5','9', 858+ '\3','5','6','0', '\3','5','6','1', '\3','5','6','2', '\3','5','6','3', '\3','5','6','4', 859+ '\3','5','6','5', '\3','5','6','6', '\3','5','6','7', '\3','5','6','8', '\3','5','6','9', 860+ '\3','5','7','0', '\3','5','7','1', '\3','5','7','2', '\3','5','7','3', '\3','5','7','4', 861+ '\3','5','7','5', '\3','5','7','6', '\3','5','7','7', '\3','5','7','8', '\3','5','7','9', 862+ '\3','5','8','0', '\3','5','8','1', '\3','5','8','2', '\3','5','8','3', '\3','5','8','4', 863+ '\3','5','8','5', '\3','5','8','6', '\3','5','8','7', '\3','5','8','8', '\3','5','8','9', 864+ '\3','5','9','0', '\3','5','9','1', '\3','5','9','2', '\3','5','9','3', '\3','5','9','4', 865+ '\3','5','9','5', '\3','5','9','6', '\3','5','9','7', '\3','5','9','8', '\3','5','9','9', 866+ '\3','6','0','0', '\3','6','0','1', '\3','6','0','2', '\3','6','0','3', '\3','6','0','4', 867+ '\3','6','0','5', '\3','6','0','6', '\3','6','0','7', '\3','6','0','8', '\3','6','0','9', 868+ '\3','6','1','0', '\3','6','1','1', '\3','6','1','2', '\3','6','1','3', '\3','6','1','4', 869+ '\3','6','1','5', '\3','6','1','6', '\3','6','1','7', '\3','6','1','8', '\3','6','1','9', 870+ '\3','6','2','0', '\3','6','2','1', '\3','6','2','2', '\3','6','2','3', '\3','6','2','4', 871+ '\3','6','2','5', '\3','6','2','6', '\3','6','2','7', '\3','6','2','8', '\3','6','2','9', 872+ '\3','6','3','0', '\3','6','3','1', '\3','6','3','2', '\3','6','3','3', '\3','6','3','4', 873+ '\3','6','3','5', '\3','6','3','6', '\3','6','3','7', '\3','6','3','8', '\3','6','3','9', 874+ '\3','6','4','0', '\3','6','4','1', '\3','6','4','2', '\3','6','4','3', '\3','6','4','4', 875+ '\3','6','4','5', '\3','6','4','6', '\3','6','4','7', '\3','6','4','8', '\3','6','4','9', 876+ '\3','6','5','0', '\3','6','5','1', '\3','6','5','2', '\3','6','5','3', '\3','6','5','4', 877+ '\3','6','5','5', '\3','6','5','6', '\3','6','5','7', '\3','6','5','8', '\3','6','5','9', 878+ '\3','6','6','0', '\3','6','6','1', '\3','6','6','2', '\3','6','6','3', '\3','6','6','4', 879+ '\3','6','6','5', '\3','6','6','6', '\3','6','6','7', '\3','6','6','8', '\3','6','6','9', 880+ '\3','6','7','0', '\3','6','7','1', '\3','6','7','2', '\3','6','7','3', '\3','6','7','4', 881+ '\3','6','7','5', '\3','6','7','6', '\3','6','7','7', '\3','6','7','8', '\3','6','7','9', 882+ '\3','6','8','0', '\3','6','8','1', '\3','6','8','2', '\3','6','8','3', '\3','6','8','4', 883+ '\3','6','8','5', '\3','6','8','6', '\3','6','8','7', '\3','6','8','8', '\3','6','8','9', 884+ '\3','6','9','0', '\3','6','9','1', '\3','6','9','2', '\3','6','9','3', '\3','6','9','4', 885+ '\3','6','9','5', '\3','6','9','6', '\3','6','9','7', '\3','6','9','8', '\3','6','9','9', 886+ '\3','7','0','0', '\3','7','0','1', '\3','7','0','2', '\3','7','0','3', '\3','7','0','4', 887+ '\3','7','0','5', '\3','7','0','6', '\3','7','0','7', '\3','7','0','8', '\3','7','0','9', 888+ '\3','7','1','0', '\3','7','1','1', '\3','7','1','2', '\3','7','1','3', '\3','7','1','4', 889+ '\3','7','1','5', '\3','7','1','6', '\3','7','1','7', '\3','7','1','8', '\3','7','1','9', 890+ '\3','7','2','0', '\3','7','2','1', '\3','7','2','2', '\3','7','2','3', '\3','7','2','4', 891+ '\3','7','2','5', '\3','7','2','6', '\3','7','2','7', '\3','7','2','8', '\3','7','2','9', 892+ '\3','7','3','0', '\3','7','3','1', '\3','7','3','2', '\3','7','3','3', '\3','7','3','4', 893+ '\3','7','3','5', '\3','7','3','6', '\3','7','3','7', '\3','7','3','8', '\3','7','3','9', 894+ '\3','7','4','0', '\3','7','4','1', '\3','7','4','2', '\3','7','4','3', '\3','7','4','4', 895+ '\3','7','4','5', '\3','7','4','6', '\3','7','4','7', '\3','7','4','8', '\3','7','4','9', 896+ '\3','7','5','0', '\3','7','5','1', '\3','7','5','2', '\3','7','5','3', '\3','7','5','4', 897+ '\3','7','5','5', '\3','7','5','6', '\3','7','5','7', '\3','7','5','8', '\3','7','5','9', 898+ '\3','7','6','0', '\3','7','6','1', '\3','7','6','2', '\3','7','6','3', '\3','7','6','4', 899+ '\3','7','6','5', '\3','7','6','6', '\3','7','6','7', '\3','7','6','8', '\3','7','6','9', 900+ '\3','7','7','0', '\3','7','7','1', '\3','7','7','2', '\3','7','7','3', '\3','7','7','4', 901+ '\3','7','7','5', '\3','7','7','6', '\3','7','7','7', '\3','7','7','8', '\3','7','7','9', 902+ '\3','7','8','0', '\3','7','8','1', '\3','7','8','2', '\3','7','8','3', '\3','7','8','4', 903+ '\3','7','8','5', '\3','7','8','6', '\3','7','8','7', '\3','7','8','8', '\3','7','8','9', 904+ '\3','7','9','0', '\3','7','9','1', '\3','7','9','2', '\3','7','9','3', '\3','7','9','4', 905+ '\3','7','9','5', '\3','7','9','6', '\3','7','9','7', '\3','7','9','8', '\3','7','9','9', 906+ '\3','8','0','0', '\3','8','0','1', '\3','8','0','2', '\3','8','0','3', '\3','8','0','4', 907+ '\3','8','0','5', '\3','8','0','6', '\3','8','0','7', '\3','8','0','8', '\3','8','0','9', 908+ '\3','8','1','0', '\3','8','1','1', '\3','8','1','2', '\3','8','1','3', '\3','8','1','4', 909+ '\3','8','1','5', '\3','8','1','6', '\3','8','1','7', '\3','8','1','8', '\3','8','1','9', 910+ '\3','8','2','0', '\3','8','2','1', '\3','8','2','2', '\3','8','2','3', '\3','8','2','4', 911+ '\3','8','2','5', '\3','8','2','6', '\3','8','2','7', '\3','8','2','8', '\3','8','2','9', 912+ '\3','8','3','0', '\3','8','3','1', '\3','8','3','2', '\3','8','3','3', '\3','8','3','4', 913+ '\3','8','3','5', '\3','8','3','6', '\3','8','3','7', '\3','8','3','8', '\3','8','3','9', 914+ '\3','8','4','0', '\3','8','4','1', '\3','8','4','2', '\3','8','4','3', '\3','8','4','4', 915+ '\3','8','4','5', '\3','8','4','6', '\3','8','4','7', '\3','8','4','8', '\3','8','4','9', 916+ '\3','8','5','0', '\3','8','5','1', '\3','8','5','2', '\3','8','5','3', '\3','8','5','4', 917+ '\3','8','5','5', '\3','8','5','6', '\3','8','5','7', '\3','8','5','8', '\3','8','5','9', 918+ '\3','8','6','0', '\3','8','6','1', '\3','8','6','2', '\3','8','6','3', '\3','8','6','4', 919+ '\3','8','6','5', '\3','8','6','6', '\3','8','6','7', '\3','8','6','8', '\3','8','6','9', 920+ '\3','8','7','0', '\3','8','7','1', '\3','8','7','2', '\3','8','7','3', '\3','8','7','4', 921+ '\3','8','7','5', '\3','8','7','6', '\3','8','7','7', '\3','8','7','8', '\3','8','7','9', 922+ '\3','8','8','0', '\3','8','8','1', '\3','8','8','2', '\3','8','8','3', '\3','8','8','4', 923+ '\3','8','8','5', '\3','8','8','6', '\3','8','8','7', '\3','8','8','8', '\3','8','8','9', 924+ '\3','8','9','0', '\3','8','9','1', '\3','8','9','2', '\3','8','9','3', '\3','8','9','4', 925+ '\3','8','9','5', '\3','8','9','6', '\3','8','9','7', '\3','8','9','8', '\3','8','9','9', 926+ '\3','9','0','0', '\3','9','0','1', '\3','9','0','2', '\3','9','0','3', '\3','9','0','4', 927+ '\3','9','0','5', '\3','9','0','6', '\3','9','0','7', '\3','9','0','8', '\3','9','0','9', 928+ '\3','9','1','0', '\3','9','1','1', '\3','9','1','2', '\3','9','1','3', '\3','9','1','4', 929+ '\3','9','1','5', '\3','9','1','6', '\3','9','1','7', '\3','9','1','8', '\3','9','1','9', 930+ '\3','9','2','0', '\3','9','2','1', '\3','9','2','2', '\3','9','2','3', '\3','9','2','4', 931+ '\3','9','2','5', '\3','9','2','6', '\3','9','2','7', '\3','9','2','8', '\3','9','2','9', 932+ '\3','9','3','0', '\3','9','3','1', '\3','9','3','2', '\3','9','3','3', '\3','9','3','4', 933+ '\3','9','3','5', '\3','9','3','6', '\3','9','3','7', '\3','9','3','8', '\3','9','3','9', 934+ '\3','9','4','0', '\3','9','4','1', '\3','9','4','2', '\3','9','4','3', '\3','9','4','4', 935+ '\3','9','4','5', '\3','9','4','6', '\3','9','4','7', '\3','9','4','8', '\3','9','4','9', 936+ '\3','9','5','0', '\3','9','5','1', '\3','9','5','2', '\3','9','5','3', '\3','9','5','4', 937+ '\3','9','5','5', '\3','9','5','6', '\3','9','5','7', '\3','9','5','8', '\3','9','5','9', 938+ '\3','9','6','0', '\3','9','6','1', '\3','9','6','2', '\3','9','6','3', '\3','9','6','4', 939+ '\3','9','6','5', '\3','9','6','6', '\3','9','6','7', '\3','9','6','8', '\3','9','6','9', 940+ '\3','9','7','0', '\3','9','7','1', '\3','9','7','2', '\3','9','7','3', '\3','9','7','4', 941+ '\3','9','7','5', '\3','9','7','6', '\3','9','7','7', '\3','9','7','8', '\3','9','7','9', 942+ '\3','9','8','0', '\3','9','8','1', '\3','9','8','2', '\3','9','8','3', '\3','9','8','4', 943+ '\3','9','8','5', '\3','9','8','6', '\3','9','8','7', '\3','9','8','8', '\3','9','8','9', 944+ '\3','9','9','0', '\3','9','9','1', '\3','9','9','2', '\3','9','9','3', '\3','9','9','4', 945+ '\3','9','9','5', '\3','9','9','6', '\3','9','9','7', '\3','9','9','8', '\3','9','9','9', '\0'};946+#endif947+ 948+#if defined(DEC_DPD2BCD8) && DEC_DPD2BCD8==1 && !defined(DECDPD2BCD8)949+#define DECDPD2BCD8950+ 951+const uint8_t DPD2BCD8[4096]={952+ 0,0,0,0, 0,0,1,1, 0,0,2,1, 0,0,3,1, 0,0,4,1, 0,0,5,1, 0,0,6,1, 0,0,7,1, 0,0,8,1, 953+ 0,0,9,1, 0,8,0,2, 0,8,1,2, 8,0,0,3, 8,0,1,3, 8,8,0,3, 8,8,1,3, 0,1,0,2, 0,1,1,2, 954+ 0,1,2,2, 0,1,3,2, 0,1,4,2, 0,1,5,2, 0,1,6,2, 0,1,7,2, 0,1,8,2, 0,1,9,2, 0,9,0,2, 955+ 0,9,1,2, 8,1,0,3, 8,1,1,3, 8,9,0,3, 8,9,1,3, 0,2,0,2, 0,2,1,2, 0,2,2,2, 0,2,3,2, 956+ 0,2,4,2, 0,2,5,2, 0,2,6,2, 0,2,7,2, 0,2,8,2, 0,2,9,2, 0,8,2,2, 0,8,3,2, 8,2,0,3, 957+ 8,2,1,3, 8,0,8,3, 8,0,9,3, 0,3,0,2, 0,3,1,2, 0,3,2,2, 0,3,3,2, 0,3,4,2, 0,3,5,2, 958+ 0,3,6,2, 0,3,7,2, 0,3,8,2, 0,3,9,2, 0,9,2,2, 0,9,3,2, 8,3,0,3, 8,3,1,3, 8,1,8,3, 959+ 8,1,9,3, 0,4,0,2, 0,4,1,2, 0,4,2,2, 0,4,3,2, 0,4,4,2, 0,4,5,2, 0,4,6,2, 0,4,7,2, 960+ 0,4,8,2, 0,4,9,2, 0,8,4,2, 0,8,5,2, 8,4,0,3, 8,4,1,3, 0,8,8,2, 0,8,9,2, 0,5,0,2, 961+ 0,5,1,2, 0,5,2,2, 0,5,3,2, 0,5,4,2, 0,5,5,2, 0,5,6,2, 0,5,7,2, 0,5,8,2, 0,5,9,2, 962+ 0,9,4,2, 0,9,5,2, 8,5,0,3, 8,5,1,3, 0,9,8,2, 0,9,9,2, 0,6,0,2, 0,6,1,2, 0,6,2,2, 963+ 0,6,3,2, 0,6,4,2, 0,6,5,2, 0,6,6,2, 0,6,7,2, 0,6,8,2, 0,6,9,2, 0,8,6,2, 0,8,7,2, 964+ 8,6,0,3, 8,6,1,3, 8,8,8,3, 8,8,9,3, 0,7,0,2, 0,7,1,2, 0,7,2,2, 0,7,3,2, 0,7,4,2, 965+ 0,7,5,2, 0,7,6,2, 0,7,7,2, 0,7,8,2, 0,7,9,2, 0,9,6,2, 0,9,7,2, 8,7,0,3, 8,7,1,3, 966+ 8,9,8,3, 8,9,9,3, 1,0,0,3, 1,0,1,3, 1,0,2,3, 1,0,3,3, 1,0,4,3, 1,0,5,3, 1,0,6,3, 967+ 1,0,7,3, 1,0,8,3, 1,0,9,3, 1,8,0,3, 1,8,1,3, 9,0,0,3, 9,0,1,3, 9,8,0,3, 9,8,1,3, 968+ 1,1,0,3, 1,1,1,3, 1,1,2,3, 1,1,3,3, 1,1,4,3, 1,1,5,3, 1,1,6,3, 1,1,7,3, 1,1,8,3, 969+ 1,1,9,3, 1,9,0,3, 1,9,1,3, 9,1,0,3, 9,1,1,3, 9,9,0,3, 9,9,1,3, 1,2,0,3, 1,2,1,3, 970+ 1,2,2,3, 1,2,3,3, 1,2,4,3, 1,2,5,3, 1,2,6,3, 1,2,7,3, 1,2,8,3, 1,2,9,3, 1,8,2,3, 971+ 1,8,3,3, 9,2,0,3, 9,2,1,3, 9,0,8,3, 9,0,9,3, 1,3,0,3, 1,3,1,3, 1,3,2,3, 1,3,3,3, 972+ 1,3,4,3, 1,3,5,3, 1,3,6,3, 1,3,7,3, 1,3,8,3, 1,3,9,3, 1,9,2,3, 1,9,3,3, 9,3,0,3, 973+ 9,3,1,3, 9,1,8,3, 9,1,9,3, 1,4,0,3, 1,4,1,3, 1,4,2,3, 1,4,3,3, 1,4,4,3, 1,4,5,3, 974+ 1,4,6,3, 1,4,7,3, 1,4,8,3, 1,4,9,3, 1,8,4,3, 1,8,5,3, 9,4,0,3, 9,4,1,3, 1,8,8,3, 975+ 1,8,9,3, 1,5,0,3, 1,5,1,3, 1,5,2,3, 1,5,3,3, 1,5,4,3, 1,5,5,3, 1,5,6,3, 1,5,7,3, 976+ 1,5,8,3, 1,5,9,3, 1,9,4,3, 1,9,5,3, 9,5,0,3, 9,5,1,3, 1,9,8,3, 1,9,9,3, 1,6,0,3, 977+ 1,6,1,3, 1,6,2,3, 1,6,3,3, 1,6,4,3, 1,6,5,3, 1,6,6,3, 1,6,7,3, 1,6,8,3, 1,6,9,3, 978+ 1,8,6,3, 1,8,7,3, 9,6,0,3, 9,6,1,3, 9,8,8,3, 9,8,9,3, 1,7,0,3, 1,7,1,3, 1,7,2,3, 979+ 1,7,3,3, 1,7,4,3, 1,7,5,3, 1,7,6,3, 1,7,7,3, 1,7,8,3, 1,7,9,3, 1,9,6,3, 1,9,7,3, 980+ 9,7,0,3, 9,7,1,3, 9,9,8,3, 9,9,9,3, 2,0,0,3, 2,0,1,3, 2,0,2,3, 2,0,3,3, 2,0,4,3, 981+ 2,0,5,3, 2,0,6,3, 2,0,7,3, 2,0,8,3, 2,0,9,3, 2,8,0,3, 2,8,1,3, 8,0,2,3, 8,0,3,3, 982+ 8,8,2,3, 8,8,3,3, 2,1,0,3, 2,1,1,3, 2,1,2,3, 2,1,3,3, 2,1,4,3, 2,1,5,3, 2,1,6,3, 983+ 2,1,7,3, 2,1,8,3, 2,1,9,3, 2,9,0,3, 2,9,1,3, 8,1,2,3, 8,1,3,3, 8,9,2,3, 8,9,3,3, 984+ 2,2,0,3, 2,2,1,3, 2,2,2,3, 2,2,3,3, 2,2,4,3, 2,2,5,3, 2,2,6,3, 2,2,7,3, 2,2,8,3, 985+ 2,2,9,3, 2,8,2,3, 2,8,3,3, 8,2,2,3, 8,2,3,3, 8,2,8,3, 8,2,9,3, 2,3,0,3, 2,3,1,3, 986+ 2,3,2,3, 2,3,3,3, 2,3,4,3, 2,3,5,3, 2,3,6,3, 2,3,7,3, 2,3,8,3, 2,3,9,3, 2,9,2,3, 987+ 2,9,3,3, 8,3,2,3, 8,3,3,3, 8,3,8,3, 8,3,9,3, 2,4,0,3, 2,4,1,3, 2,4,2,3, 2,4,3,3, 988+ 2,4,4,3, 2,4,5,3, 2,4,6,3, 2,4,7,3, 2,4,8,3, 2,4,9,3, 2,8,4,3, 2,8,5,3, 8,4,2,3, 989+ 8,4,3,3, 2,8,8,3, 2,8,9,3, 2,5,0,3, 2,5,1,3, 2,5,2,3, 2,5,3,3, 2,5,4,3, 2,5,5,3, 990+ 2,5,6,3, 2,5,7,3, 2,5,8,3, 2,5,9,3, 2,9,4,3, 2,9,5,3, 8,5,2,3, 8,5,3,3, 2,9,8,3, 991+ 2,9,9,3, 2,6,0,3, 2,6,1,3, 2,6,2,3, 2,6,3,3, 2,6,4,3, 2,6,5,3, 2,6,6,3, 2,6,7,3, 992+ 2,6,8,3, 2,6,9,3, 2,8,6,3, 2,8,7,3, 8,6,2,3, 8,6,3,3, 8,8,8,3, 8,8,9,3, 2,7,0,3, 993+ 2,7,1,3, 2,7,2,3, 2,7,3,3, 2,7,4,3, 2,7,5,3, 2,7,6,3, 2,7,7,3, 2,7,8,3, 2,7,9,3, 994+ 2,9,6,3, 2,9,7,3, 8,7,2,3, 8,7,3,3, 8,9,8,3, 8,9,9,3, 3,0,0,3, 3,0,1,3, 3,0,2,3, 995+ 3,0,3,3, 3,0,4,3, 3,0,5,3, 3,0,6,3, 3,0,7,3, 3,0,8,3, 3,0,9,3, 3,8,0,3, 3,8,1,3, 996+ 9,0,2,3, 9,0,3,3, 9,8,2,3, 9,8,3,3, 3,1,0,3, 3,1,1,3, 3,1,2,3, 3,1,3,3, 3,1,4,3, 997+ 3,1,5,3, 3,1,6,3, 3,1,7,3, 3,1,8,3, 3,1,9,3, 3,9,0,3, 3,9,1,3, 9,1,2,3, 9,1,3,3, 998+ 9,9,2,3, 9,9,3,3, 3,2,0,3, 3,2,1,3, 3,2,2,3, 3,2,3,3, 3,2,4,3, 3,2,5,3, 3,2,6,3, 999+ 3,2,7,3, 3,2,8,3, 3,2,9,3, 3,8,2,3, 3,8,3,3, 9,2,2,3, 9,2,3,3, 9,2,8,3, 9,2,9,3, 1000+ 3,3,0,3, 3,3,1,3, 3,3,2,3, 3,3,3,3, 3,3,4,3, 3,3,5,3, 3,3,6,3, 3,3,7,3, 3,3,8,3, 1001+ 3,3,9,3, 3,9,2,3, 3,9,3,3, 9,3,2,3, 9,3,3,3, 9,3,8,3, 9,3,9,3, 3,4,0,3, 3,4,1,3, 1002+ 3,4,2,3, 3,4,3,3, 3,4,4,3, 3,4,5,3, 3,4,6,3, 3,4,7,3, 3,4,8,3, 3,4,9,3, 3,8,4,3, 1003+ 3,8,5,3, 9,4,2,3, 9,4,3,3, 3,8,8,3, 3,8,9,3, 3,5,0,3, 3,5,1,3, 3,5,2,3, 3,5,3,3, 1004+ 3,5,4,3, 3,5,5,3, 3,5,6,3, 3,5,7,3, 3,5,8,3, 3,5,9,3, 3,9,4,3, 3,9,5,3, 9,5,2,3, 1005+ 9,5,3,3, 3,9,8,3, 3,9,9,3, 3,6,0,3, 3,6,1,3, 3,6,2,3, 3,6,3,3, 3,6,4,3, 3,6,5,3, 1006+ 3,6,6,3, 3,6,7,3, 3,6,8,3, 3,6,9,3, 3,8,6,3, 3,8,7,3, 9,6,2,3, 9,6,3,3, 9,8,8,3, 1007+ 9,8,9,3, 3,7,0,3, 3,7,1,3, 3,7,2,3, 3,7,3,3, 3,7,4,3, 3,7,5,3, 3,7,6,3, 3,7,7,3, 1008+ 3,7,8,3, 3,7,9,3, 3,9,6,3, 3,9,7,3, 9,7,2,3, 9,7,3,3, 9,9,8,3, 9,9,9,3, 4,0,0,3, 1009+ 4,0,1,3, 4,0,2,3, 4,0,3,3, 4,0,4,3, 4,0,5,3, 4,0,6,3, 4,0,7,3, 4,0,8,3, 4,0,9,3, 1010+ 4,8,0,3, 4,8,1,3, 8,0,4,3, 8,0,5,3, 8,8,4,3, 8,8,5,3, 4,1,0,3, 4,1,1,3, 4,1,2,3, 1011+ 4,1,3,3, 4,1,4,3, 4,1,5,3, 4,1,6,3, 4,1,7,3, 4,1,8,3, 4,1,9,3, 4,9,0,3, 4,9,1,3, 1012+ 8,1,4,3, 8,1,5,3, 8,9,4,3, 8,9,5,3, 4,2,0,3, 4,2,1,3, 4,2,2,3, 4,2,3,3, 4,2,4,3, 1013+ 4,2,5,3, 4,2,6,3, 4,2,7,3, 4,2,8,3, 4,2,9,3, 4,8,2,3, 4,8,3,3, 8,2,4,3, 8,2,5,3, 1014+ 8,4,8,3, 8,4,9,3, 4,3,0,3, 4,3,1,3, 4,3,2,3, 4,3,3,3, 4,3,4,3, 4,3,5,3, 4,3,6,3, 1015+ 4,3,7,3, 4,3,8,3, 4,3,9,3, 4,9,2,3, 4,9,3,3, 8,3,4,3, 8,3,5,3, 8,5,8,3, 8,5,9,3, 1016+ 4,4,0,3, 4,4,1,3, 4,4,2,3, 4,4,3,3, 4,4,4,3, 4,4,5,3, 4,4,6,3, 4,4,7,3, 4,4,8,3, 1017+ 4,4,9,3, 4,8,4,3, 4,8,5,3, 8,4,4,3, 8,4,5,3, 4,8,8,3, 4,8,9,3, 4,5,0,3, 4,5,1,3, 1018+ 4,5,2,3, 4,5,3,3, 4,5,4,3, 4,5,5,3, 4,5,6,3, 4,5,7,3, 4,5,8,3, 4,5,9,3, 4,9,4,3, 1019+ 4,9,5,3, 8,5,4,3, 8,5,5,3, 4,9,8,3, 4,9,9,3, 4,6,0,3, 4,6,1,3, 4,6,2,3, 4,6,3,3, 1020+ 4,6,4,3, 4,6,5,3, 4,6,6,3, 4,6,7,3, 4,6,8,3, 4,6,9,3, 4,8,6,3, 4,8,7,3, 8,6,4,3, 1021+ 8,6,5,3, 8,8,8,3, 8,8,9,3, 4,7,0,3, 4,7,1,3, 4,7,2,3, 4,7,3,3, 4,7,4,3, 4,7,5,3, 1022+ 4,7,6,3, 4,7,7,3, 4,7,8,3, 4,7,9,3, 4,9,6,3, 4,9,7,3, 8,7,4,3, 8,7,5,3, 8,9,8,3, 1023+ 8,9,9,3, 5,0,0,3, 5,0,1,3, 5,0,2,3, 5,0,3,3, 5,0,4,3, 5,0,5,3, 5,0,6,3, 5,0,7,3, 1024+ 5,0,8,3, 5,0,9,3, 5,8,0,3, 5,8,1,3, 9,0,4,3, 9,0,5,3, 9,8,4,3, 9,8,5,3, 5,1,0,3, 1025+ 5,1,1,3, 5,1,2,3, 5,1,3,3, 5,1,4,3, 5,1,5,3, 5,1,6,3, 5,1,7,3, 5,1,8,3, 5,1,9,3, 1026+ 5,9,0,3, 5,9,1,3, 9,1,4,3, 9,1,5,3, 9,9,4,3, 9,9,5,3, 5,2,0,3, 5,2,1,3, 5,2,2,3, 1027+ 5,2,3,3, 5,2,4,3, 5,2,5,3, 5,2,6,3, 5,2,7,3, 5,2,8,3, 5,2,9,3, 5,8,2,3, 5,8,3,3, 1028+ 9,2,4,3, 9,2,5,3, 9,4,8,3, 9,4,9,3, 5,3,0,3, 5,3,1,3, 5,3,2,3, 5,3,3,3, 5,3,4,3, 1029+ 5,3,5,3, 5,3,6,3, 5,3,7,3, 5,3,8,3, 5,3,9,3, 5,9,2,3, 5,9,3,3, 9,3,4,3, 9,3,5,3, 1030+ 9,5,8,3, 9,5,9,3, 5,4,0,3, 5,4,1,3, 5,4,2,3, 5,4,3,3, 5,4,4,3, 5,4,5,3, 5,4,6,3, 1031+ 5,4,7,3, 5,4,8,3, 5,4,9,3, 5,8,4,3, 5,8,5,3, 9,4,4,3, 9,4,5,3, 5,8,8,3, 5,8,9,3, 1032+ 5,5,0,3, 5,5,1,3, 5,5,2,3, 5,5,3,3, 5,5,4,3, 5,5,5,3, 5,5,6,3, 5,5,7,3, 5,5,8,3, 1033+ 5,5,9,3, 5,9,4,3, 5,9,5,3, 9,5,4,3, 9,5,5,3, 5,9,8,3, 5,9,9,3, 5,6,0,3, 5,6,1,3, 1034+ 5,6,2,3, 5,6,3,3, 5,6,4,3, 5,6,5,3, 5,6,6,3, 5,6,7,3, 5,6,8,3, 5,6,9,3, 5,8,6,3, 1035+ 5,8,7,3, 9,6,4,3, 9,6,5,3, 9,8,8,3, 9,8,9,3, 5,7,0,3, 5,7,1,3, 5,7,2,3, 5,7,3,3, 1036+ 5,7,4,3, 5,7,5,3, 5,7,6,3, 5,7,7,3, 5,7,8,3, 5,7,9,3, 5,9,6,3, 5,9,7,3, 9,7,4,3, 1037+ 9,7,5,3, 9,9,8,3, 9,9,9,3, 6,0,0,3, 6,0,1,3, 6,0,2,3, 6,0,3,3, 6,0,4,3, 6,0,5,3, 1038+ 6,0,6,3, 6,0,7,3, 6,0,8,3, 6,0,9,3, 6,8,0,3, 6,8,1,3, 8,0,6,3, 8,0,7,3, 8,8,6,3, 1039+ 8,8,7,3, 6,1,0,3, 6,1,1,3, 6,1,2,3, 6,1,3,3, 6,1,4,3, 6,1,5,3, 6,1,6,3, 6,1,7,3, 1040+ 6,1,8,3, 6,1,9,3, 6,9,0,3, 6,9,1,3, 8,1,6,3, 8,1,7,3, 8,9,6,3, 8,9,7,3, 6,2,0,3, 1041+ 6,2,1,3, 6,2,2,3, 6,2,3,3, 6,2,4,3, 6,2,5,3, 6,2,6,3, 6,2,7,3, 6,2,8,3, 6,2,9,3, 1042+ 6,8,2,3, 6,8,3,3, 8,2,6,3, 8,2,7,3, 8,6,8,3, 8,6,9,3, 6,3,0,3, 6,3,1,3, 6,3,2,3, 1043+ 6,3,3,3, 6,3,4,3, 6,3,5,3, 6,3,6,3, 6,3,7,3, 6,3,8,3, 6,3,9,3, 6,9,2,3, 6,9,3,3, 1044+ 8,3,6,3, 8,3,7,3, 8,7,8,3, 8,7,9,3, 6,4,0,3, 6,4,1,3, 6,4,2,3, 6,4,3,3, 6,4,4,3, 1045+ 6,4,5,3, 6,4,6,3, 6,4,7,3, 6,4,8,3, 6,4,9,3, 6,8,4,3, 6,8,5,3, 8,4,6,3, 8,4,7,3, 1046+ 6,8,8,3, 6,8,9,3, 6,5,0,3, 6,5,1,3, 6,5,2,3, 6,5,3,3, 6,5,4,3, 6,5,5,3, 6,5,6,3, 1047+ 6,5,7,3, 6,5,8,3, 6,5,9,3, 6,9,4,3, 6,9,5,3, 8,5,6,3, 8,5,7,3, 6,9,8,3, 6,9,9,3, 1048+ 6,6,0,3, 6,6,1,3, 6,6,2,3, 6,6,3,3, 6,6,4,3, 6,6,5,3, 6,6,6,3, 6,6,7,3, 6,6,8,3, 1049+ 6,6,9,3, 6,8,6,3, 6,8,7,3, 8,6,6,3, 8,6,7,3, 8,8,8,3, 8,8,9,3, 6,7,0,3, 6,7,1,3, 1050+ 6,7,2,3, 6,7,3,3, 6,7,4,3, 6,7,5,3, 6,7,6,3, 6,7,7,3, 6,7,8,3, 6,7,9,3, 6,9,6,3, 1051+ 6,9,7,3, 8,7,6,3, 8,7,7,3, 8,9,8,3, 8,9,9,3, 7,0,0,3, 7,0,1,3, 7,0,2,3, 7,0,3,3, 1052+ 7,0,4,3, 7,0,5,3, 7,0,6,3, 7,0,7,3, 7,0,8,3, 7,0,9,3, 7,8,0,3, 7,8,1,3, 9,0,6,3, 1053+ 9,0,7,3, 9,8,6,3, 9,8,7,3, 7,1,0,3, 7,1,1,3, 7,1,2,3, 7,1,3,3, 7,1,4,3, 7,1,5,3, 1054+ 7,1,6,3, 7,1,7,3, 7,1,8,3, 7,1,9,3, 7,9,0,3, 7,9,1,3, 9,1,6,3, 9,1,7,3, 9,9,6,3, 1055+ 9,9,7,3, 7,2,0,3, 7,2,1,3, 7,2,2,3, 7,2,3,3, 7,2,4,3, 7,2,5,3, 7,2,6,3, 7,2,7,3, 1056+ 7,2,8,3, 7,2,9,3, 7,8,2,3, 7,8,3,3, 9,2,6,3, 9,2,7,3, 9,6,8,3, 9,6,9,3, 7,3,0,3, 1057+ 7,3,1,3, 7,3,2,3, 7,3,3,3, 7,3,4,3, 7,3,5,3, 7,3,6,3, 7,3,7,3, 7,3,8,3, 7,3,9,3, 1058+ 7,9,2,3, 7,9,3,3, 9,3,6,3, 9,3,7,3, 9,7,8,3, 9,7,9,3, 7,4,0,3, 7,4,1,3, 7,4,2,3, 1059+ 7,4,3,3, 7,4,4,3, 7,4,5,3, 7,4,6,3, 7,4,7,3, 7,4,8,3, 7,4,9,3, 7,8,4,3, 7,8,5,3, 1060+ 9,4,6,3, 9,4,7,3, 7,8,8,3, 7,8,9,3, 7,5,0,3, 7,5,1,3, 7,5,2,3, 7,5,3,3, 7,5,4,3, 1061+ 7,5,5,3, 7,5,6,3, 7,5,7,3, 7,5,8,3, 7,5,9,3, 7,9,4,3, 7,9,5,3, 9,5,6,3, 9,5,7,3, 1062+ 7,9,8,3, 7,9,9,3, 7,6,0,3, 7,6,1,3, 7,6,2,3, 7,6,3,3, 7,6,4,3, 7,6,5,3, 7,6,6,3, 1063+ 7,6,7,3, 7,6,8,3, 7,6,9,3, 7,8,6,3, 7,8,7,3, 9,6,6,3, 9,6,7,3, 9,8,8,3, 9,8,9,3, 1064+ 7,7,0,3, 7,7,1,3, 7,7,2,3, 7,7,3,3, 7,7,4,3, 7,7,5,3, 7,7,6,3, 7,7,7,3, 7,7,8,3, 1065+ 7,7,9,3, 7,9,6,3, 7,9,7,3, 9,7,6,3, 9,7,7,3, 9,9,8,3, 9,9,9,3};1066+#endif1067+ 1068+#if defined(DEC_BIN2BCD8) && DEC_BIN2BCD8==1 && !defined(DECBIN2BCD8)1069+#define DECBIN2BCD81070+ 1071+const uint8_t BIN2BCD8[4000]={1072+ 0,0,0,0, 0,0,1,1, 0,0,2,1, 0,0,3,1, 0,0,4,1, 0,0,5,1, 0,0,6,1, 0,0,7,1, 0,0,8,1, 1073+ 0,0,9,1, 0,1,0,2, 0,1,1,2, 0,1,2,2, 0,1,3,2, 0,1,4,2, 0,1,5,2, 0,1,6,2, 0,1,7,2, 1074+ 0,1,8,2, 0,1,9,2, 0,2,0,2, 0,2,1,2, 0,2,2,2, 0,2,3,2, 0,2,4,2, 0,2,5,2, 0,2,6,2, 1075+ 0,2,7,2, 0,2,8,2, 0,2,9,2, 0,3,0,2, 0,3,1,2, 0,3,2,2, 0,3,3,2, 0,3,4,2, 0,3,5,2, 1076+ 0,3,6,2, 0,3,7,2, 0,3,8,2, 0,3,9,2, 0,4,0,2, 0,4,1,2, 0,4,2,2, 0,4,3,2, 0,4,4,2, 1077+ 0,4,5,2, 0,4,6,2, 0,4,7,2, 0,4,8,2, 0,4,9,2, 0,5,0,2, 0,5,1,2, 0,5,2,2, 0,5,3,2, 1078+ 0,5,4,2, 0,5,5,2, 0,5,6,2, 0,5,7,2, 0,5,8,2, 0,5,9,2, 0,6,0,2, 0,6,1,2, 0,6,2,2, 1079+ 0,6,3,2, 0,6,4,2, 0,6,5,2, 0,6,6,2, 0,6,7,2, 0,6,8,2, 0,6,9,2, 0,7,0,2, 0,7,1,2, 1080+ 0,7,2,2, 0,7,3,2, 0,7,4,2, 0,7,5,2, 0,7,6,2, 0,7,7,2, 0,7,8,2, 0,7,9,2, 0,8,0,2, 1081+ 0,8,1,2, 0,8,2,2, 0,8,3,2, 0,8,4,2, 0,8,5,2, 0,8,6,2, 0,8,7,2, 0,8,8,2, 0,8,9,2, 1082+ 0,9,0,2, 0,9,1,2, 0,9,2,2, 0,9,3,2, 0,9,4,2, 0,9,5,2, 0,9,6,2, 0,9,7,2, 0,9,8,2, 1083+ 0,9,9,2, 1,0,0,3, 1,0,1,3, 1,0,2,3, 1,0,3,3, 1,0,4,3, 1,0,5,3, 1,0,6,3, 1,0,7,3, 1084+ 1,0,8,3, 1,0,9,3, 1,1,0,3, 1,1,1,3, 1,1,2,3, 1,1,3,3, 1,1,4,3, 1,1,5,3, 1,1,6,3, 1085+ 1,1,7,3, 1,1,8,3, 1,1,9,3, 1,2,0,3, 1,2,1,3, 1,2,2,3, 1,2,3,3, 1,2,4,3, 1,2,5,3, 1086+ 1,2,6,3, 1,2,7,3, 1,2,8,3, 1,2,9,3, 1,3,0,3, 1,3,1,3, 1,3,2,3, 1,3,3,3, 1,3,4,3, 1087+ 1,3,5,3, 1,3,6,3, 1,3,7,3, 1,3,8,3, 1,3,9,3, 1,4,0,3, 1,4,1,3, 1,4,2,3, 1,4,3,3, 1088+ 1,4,4,3, 1,4,5,3, 1,4,6,3, 1,4,7,3, 1,4,8,3, 1,4,9,3, 1,5,0,3, 1,5,1,3, 1,5,2,3, 1089+ 1,5,3,3, 1,5,4,3, 1,5,5,3, 1,5,6,3, 1,5,7,3, 1,5,8,3, 1,5,9,3, 1,6,0,3, 1,6,1,3, 1090+ 1,6,2,3, 1,6,3,3, 1,6,4,3, 1,6,5,3, 1,6,6,3, 1,6,7,3, 1,6,8,3, 1,6,9,3, 1,7,0,3, 1091+ 1,7,1,3, 1,7,2,3, 1,7,3,3, 1,7,4,3, 1,7,5,3, 1,7,6,3, 1,7,7,3, 1,7,8,3, 1,7,9,3, 1092+ 1,8,0,3, 1,8,1,3, 1,8,2,3, 1,8,3,3, 1,8,4,3, 1,8,5,3, 1,8,6,3, 1,8,7,3, 1,8,8,3, 1093+ 1,8,9,3, 1,9,0,3, 1,9,1,3, 1,9,2,3, 1,9,3,3, 1,9,4,3, 1,9,5,3, 1,9,6,3, 1,9,7,3, 1094+ 1,9,8,3, 1,9,9,3, 2,0,0,3, 2,0,1,3, 2,0,2,3, 2,0,3,3, 2,0,4,3, 2,0,5,3, 2,0,6,3, 1095+ 2,0,7,3, 2,0,8,3, 2,0,9,3, 2,1,0,3, 2,1,1,3, 2,1,2,3, 2,1,3,3, 2,1,4,3, 2,1,5,3, 1096+ 2,1,6,3, 2,1,7,3, 2,1,8,3, 2,1,9,3, 2,2,0,3, 2,2,1,3, 2,2,2,3, 2,2,3,3, 2,2,4,3, 1097+ 2,2,5,3, 2,2,6,3, 2,2,7,3, 2,2,8,3, 2,2,9,3, 2,3,0,3, 2,3,1,3, 2,3,2,3, 2,3,3,3, 1098+ 2,3,4,3, 2,3,5,3, 2,3,6,3, 2,3,7,3, 2,3,8,3, 2,3,9,3, 2,4,0,3, 2,4,1,3, 2,4,2,3, 1099+ 2,4,3,3, 2,4,4,3, 2,4,5,3, 2,4,6,3, 2,4,7,3, 2,4,8,3, 2,4,9,3, 2,5,0,3, 2,5,1,3, 1100+ 2,5,2,3, 2,5,3,3, 2,5,4,3, 2,5,5,3, 2,5,6,3, 2,5,7,3, 2,5,8,3, 2,5,9,3, 2,6,0,3, 1101+ 2,6,1,3, 2,6,2,3, 2,6,3,3, 2,6,4,3, 2,6,5,3, 2,6,6,3, 2,6,7,3, 2,6,8,3, 2,6,9,3, 1102+ 2,7,0,3, 2,7,1,3, 2,7,2,3, 2,7,3,3, 2,7,4,3, 2,7,5,3, 2,7,6,3, 2,7,7,3, 2,7,8,3, 1103+ 2,7,9,3, 2,8,0,3, 2,8,1,3, 2,8,2,3, 2,8,3,3, 2,8,4,3, 2,8,5,3, 2,8,6,3, 2,8,7,3, 1104+ 2,8,8,3, 2,8,9,3, 2,9,0,3, 2,9,1,3, 2,9,2,3, 2,9,3,3, 2,9,4,3, 2,9,5,3, 2,9,6,3, 1105+ 2,9,7,3, 2,9,8,3, 2,9,9,3, 3,0,0,3, 3,0,1,3, 3,0,2,3, 3,0,3,3, 3,0,4,3, 3,0,5,3, 1106+ 3,0,6,3, 3,0,7,3, 3,0,8,3, 3,0,9,3, 3,1,0,3, 3,1,1,3, 3,1,2,3, 3,1,3,3, 3,1,4,3, 1107+ 3,1,5,3, 3,1,6,3, 3,1,7,3, 3,1,8,3, 3,1,9,3, 3,2,0,3, 3,2,1,3, 3,2,2,3, 3,2,3,3, 1108+ 3,2,4,3, 3,2,5,3, 3,2,6,3, 3,2,7,3, 3,2,8,3, 3,2,9,3, 3,3,0,3, 3,3,1,3, 3,3,2,3, 1109+ 3,3,3,3, 3,3,4,3, 3,3,5,3, 3,3,6,3, 3,3,7,3, 3,3,8,3, 3,3,9,3, 3,4,0,3, 3,4,1,3, 1110+ 3,4,2,3, 3,4,3,3, 3,4,4,3, 3,4,5,3, 3,4,6,3, 3,4,7,3, 3,4,8,3, 3,4,9,3, 3,5,0,3, 1111+ 3,5,1,3, 3,5,2,3, 3,5,3,3, 3,5,4,3, 3,5,5,3, 3,5,6,3, 3,5,7,3, 3,5,8,3, 3,5,9,3, 1112+ 3,6,0,3, 3,6,1,3, 3,6,2,3, 3,6,3,3, 3,6,4,3, 3,6,5,3, 3,6,6,3, 3,6,7,3, 3,6,8,3, 1113+ 3,6,9,3, 3,7,0,3, 3,7,1,3, 3,7,2,3, 3,7,3,3, 3,7,4,3, 3,7,5,3, 3,7,6,3, 3,7,7,3, 1114+ 3,7,8,3, 3,7,9,3, 3,8,0,3, 3,8,1,3, 3,8,2,3, 3,8,3,3, 3,8,4,3, 3,8,5,3, 3,8,6,3, 1115+ 3,8,7,3, 3,8,8,3, 3,8,9,3, 3,9,0,3, 3,9,1,3, 3,9,2,3, 3,9,3,3, 3,9,4,3, 3,9,5,3, 1116+ 3,9,6,3, 3,9,7,3, 3,9,8,3, 3,9,9,3, 4,0,0,3, 4,0,1,3, 4,0,2,3, 4,0,3,3, 4,0,4,3, 1117+ 4,0,5,3, 4,0,6,3, 4,0,7,3, 4,0,8,3, 4,0,9,3, 4,1,0,3, 4,1,1,3, 4,1,2,3, 4,1,3,3, 1118+ 4,1,4,3, 4,1,5,3, 4,1,6,3, 4,1,7,3, 4,1,8,3, 4,1,9,3, 4,2,0,3, 4,2,1,3, 4,2,2,3, 1119+ 4,2,3,3, 4,2,4,3, 4,2,5,3, 4,2,6,3, 4,2,7,3, 4,2,8,3, 4,2,9,3, 4,3,0,3, 4,3,1,3, 1120+ 4,3,2,3, 4,3,3,3, 4,3,4,3, 4,3,5,3, 4,3,6,3, 4,3,7,3, 4,3,8,3, 4,3,9,3, 4,4,0,3, 1121+ 4,4,1,3, 4,4,2,3, 4,4,3,3, 4,4,4,3, 4,4,5,3, 4,4,6,3, 4,4,7,3, 4,4,8,3, 4,4,9,3, 1122+ 4,5,0,3, 4,5,1,3, 4,5,2,3, 4,5,3,3, 4,5,4,3, 4,5,5,3, 4,5,6,3, 4,5,7,3, 4,5,8,3, 1123+ 4,5,9,3, 4,6,0,3, 4,6,1,3, 4,6,2,3, 4,6,3,3, 4,6,4,3, 4,6,5,3, 4,6,6,3, 4,6,7,3, 1124+ 4,6,8,3, 4,6,9,3, 4,7,0,3, 4,7,1,3, 4,7,2,3, 4,7,3,3, 4,7,4,3, 4,7,5,3, 4,7,6,3, 1125+ 4,7,7,3, 4,7,8,3, 4,7,9,3, 4,8,0,3, 4,8,1,3, 4,8,2,3, 4,8,3,3, 4,8,4,3, 4,8,5,3, 1126+ 4,8,6,3, 4,8,7,3, 4,8,8,3, 4,8,9,3, 4,9,0,3, 4,9,1,3, 4,9,2,3, 4,9,3,3, 4,9,4,3, 1127+ 4,9,5,3, 4,9,6,3, 4,9,7,3, 4,9,8,3, 4,9,9,3, 5,0,0,3, 5,0,1,3, 5,0,2,3, 5,0,3,3, 1128+ 5,0,4,3, 5,0,5,3, 5,0,6,3, 5,0,7,3, 5,0,8,3, 5,0,9,3, 5,1,0,3, 5,1,1,3, 5,1,2,3, 1129+ 5,1,3,3, 5,1,4,3, 5,1,5,3, 5,1,6,3, 5,1,7,3, 5,1,8,3, 5,1,9,3, 5,2,0,3, 5,2,1,3, 1130+ 5,2,2,3, 5,2,3,3, 5,2,4,3, 5,2,5,3, 5,2,6,3, 5,2,7,3, 5,2,8,3, 5,2,9,3, 5,3,0,3, 1131+ 5,3,1,3, 5,3,2,3, 5,3,3,3, 5,3,4,3, 5,3,5,3, 5,3,6,3, 5,3,7,3, 5,3,8,3, 5,3,9,3, 1132+ 5,4,0,3, 5,4,1,3, 5,4,2,3, 5,4,3,3, 5,4,4,3, 5,4,5,3, 5,4,6,3, 5,4,7,3, 5,4,8,3, 1133+ 5,4,9,3, 5,5,0,3, 5,5,1,3, 5,5,2,3, 5,5,3,3, 5,5,4,3, 5,5,5,3, 5,5,6,3, 5,5,7,3, 1134+ 5,5,8,3, 5,5,9,3, 5,6,0,3, 5,6,1,3, 5,6,2,3, 5,6,3,3, 5,6,4,3, 5,6,5,3, 5,6,6,3, 1135+ 5,6,7,3, 5,6,8,3, 5,6,9,3, 5,7,0,3, 5,7,1,3, 5,7,2,3, 5,7,3,3, 5,7,4,3, 5,7,5,3, 1136+ 5,7,6,3, 5,7,7,3, 5,7,8,3, 5,7,9,3, 5,8,0,3, 5,8,1,3, 5,8,2,3, 5,8,3,3, 5,8,4,3, 1137+ 5,8,5,3, 5,8,6,3, 5,8,7,3, 5,8,8,3, 5,8,9,3, 5,9,0,3, 5,9,1,3, 5,9,2,3, 5,9,3,3, 1138+ 5,9,4,3, 5,9,5,3, 5,9,6,3, 5,9,7,3, 5,9,8,3, 5,9,9,3, 6,0,0,3, 6,0,1,3, 6,0,2,3, 1139+ 6,0,3,3, 6,0,4,3, 6,0,5,3, 6,0,6,3, 6,0,7,3, 6,0,8,3, 6,0,9,3, 6,1,0,3, 6,1,1,3, 1140+ 6,1,2,3, 6,1,3,3, 6,1,4,3, 6,1,5,3, 6,1,6,3, 6,1,7,3, 6,1,8,3, 6,1,9,3, 6,2,0,3, 1141+ 6,2,1,3, 6,2,2,3, 6,2,3,3, 6,2,4,3, 6,2,5,3, 6,2,6,3, 6,2,7,3, 6,2,8,3, 6,2,9,3, 1142+ 6,3,0,3, 6,3,1,3, 6,3,2,3, 6,3,3,3, 6,3,4,3, 6,3,5,3, 6,3,6,3, 6,3,7,3, 6,3,8,3, 1143+ 6,3,9,3, 6,4,0,3, 6,4,1,3, 6,4,2,3, 6,4,3,3, 6,4,4,3, 6,4,5,3, 6,4,6,3, 6,4,7,3, 1144+ 6,4,8,3, 6,4,9,3, 6,5,0,3, 6,5,1,3, 6,5,2,3, 6,5,3,3, 6,5,4,3, 6,5,5,3, 6,5,6,3, 1145+ 6,5,7,3, 6,5,8,3, 6,5,9,3, 6,6,0,3, 6,6,1,3, 6,6,2,3, 6,6,3,3, 6,6,4,3, 6,6,5,3, 1146+ 6,6,6,3, 6,6,7,3, 6,6,8,3, 6,6,9,3, 6,7,0,3, 6,7,1,3, 6,7,2,3, 6,7,3,3, 6,7,4,3, 1147+ 6,7,5,3, 6,7,6,3, 6,7,7,3, 6,7,8,3, 6,7,9,3, 6,8,0,3, 6,8,1,3, 6,8,2,3, 6,8,3,3, 1148+ 6,8,4,3, 6,8,5,3, 6,8,6,3, 6,8,7,3, 6,8,8,3, 6,8,9,3, 6,9,0,3, 6,9,1,3, 6,9,2,3, 1149+ 6,9,3,3, 6,9,4,3, 6,9,5,3, 6,9,6,3, 6,9,7,3, 6,9,8,3, 6,9,9,3, 7,0,0,3, 7,0,1,3, 1150+ 7,0,2,3, 7,0,3,3, 7,0,4,3, 7,0,5,3, 7,0,6,3, 7,0,7,3, 7,0,8,3, 7,0,9,3, 7,1,0,3, 1151+ 7,1,1,3, 7,1,2,3, 7,1,3,3, 7,1,4,3, 7,1,5,3, 7,1,6,3, 7,1,7,3, 7,1,8,3, 7,1,9,3, 1152+ 7,2,0,3, 7,2,1,3, 7,2,2,3, 7,2,3,3, 7,2,4,3, 7,2,5,3, 7,2,6,3, 7,2,7,3, 7,2,8,3, 1153+ 7,2,9,3, 7,3,0,3, 7,3,1,3, 7,3,2,3, 7,3,3,3, 7,3,4,3, 7,3,5,3, 7,3,6,3, 7,3,7,3, 1154+ 7,3,8,3, 7,3,9,3, 7,4,0,3, 7,4,1,3, 7,4,2,3, 7,4,3,3, 7,4,4,3, 7,4,5,3, 7,4,6,3, 1155+ 7,4,7,3, 7,4,8,3, 7,4,9,3, 7,5,0,3, 7,5,1,3, 7,5,2,3, 7,5,3,3, 7,5,4,3, 7,5,5,3, 1156+ 7,5,6,3, 7,5,7,3, 7,5,8,3, 7,5,9,3, 7,6,0,3, 7,6,1,3, 7,6,2,3, 7,6,3,3, 7,6,4,3, 1157+ 7,6,5,3, 7,6,6,3, 7,6,7,3, 7,6,8,3, 7,6,9,3, 7,7,0,3, 7,7,1,3, 7,7,2,3, 7,7,3,3, 1158+ 7,7,4,3, 7,7,5,3, 7,7,6,3, 7,7,7,3, 7,7,8,3, 7,7,9,3, 7,8,0,3, 7,8,1,3, 7,8,2,3, 1159+ 7,8,3,3, 7,8,4,3, 7,8,5,3, 7,8,6,3, 7,8,7,3, 7,8,8,3, 7,8,9,3, 7,9,0,3, 7,9,1,3, 1160+ 7,9,2,3, 7,9,3,3, 7,9,4,3, 7,9,5,3, 7,9,6,3, 7,9,7,3, 7,9,8,3, 7,9,9,3, 8,0,0,3, 1161+ 8,0,1,3, 8,0,2,3, 8,0,3,3, 8,0,4,3, 8,0,5,3, 8,0,6,3, 8,0,7,3, 8,0,8,3, 8,0,9,3, 1162+ 8,1,0,3, 8,1,1,3, 8,1,2,3, 8,1,3,3, 8,1,4,3, 8,1,5,3, 8,1,6,3, 8,1,7,3, 8,1,8,3, 1163+ 8,1,9,3, 8,2,0,3, 8,2,1,3, 8,2,2,3, 8,2,3,3, 8,2,4,3, 8,2,5,3, 8,2,6,3, 8,2,7,3, 1164+ 8,2,8,3, 8,2,9,3, 8,3,0,3, 8,3,1,3, 8,3,2,3, 8,3,3,3, 8,3,4,3, 8,3,5,3, 8,3,6,3, 1165+ 8,3,7,3, 8,3,8,3, 8,3,9,3, 8,4,0,3, 8,4,1,3, 8,4,2,3, 8,4,3,3, 8,4,4,3, 8,4,5,3, 1166+ 8,4,6,3, 8,4,7,3, 8,4,8,3, 8,4,9,3, 8,5,0,3, 8,5,1,3, 8,5,2,3, 8,5,3,3, 8,5,4,3, 1167+ 8,5,5,3, 8,5,6,3, 8,5,7,3, 8,5,8,3, 8,5,9,3, 8,6,0,3, 8,6,1,3, 8,6,2,3, 8,6,3,3, 1168+ 8,6,4,3, 8,6,5,3, 8,6,6,3, 8,6,7,3, 8,6,8,3, 8,6,9,3, 8,7,0,3, 8,7,1,3, 8,7,2,3, 1169+ 8,7,3,3, 8,7,4,3, 8,7,5,3, 8,7,6,3, 8,7,7,3, 8,7,8,3, 8,7,9,3, 8,8,0,3, 8,8,1,3, 1170+ 8,8,2,3, 8,8,3,3, 8,8,4,3, 8,8,5,3, 8,8,6,3, 8,8,7,3, 8,8,8,3, 8,8,9,3, 8,9,0,3, 1171+ 8,9,1,3, 8,9,2,3, 8,9,3,3, 8,9,4,3, 8,9,5,3, 8,9,6,3, 8,9,7,3, 8,9,8,3, 8,9,9,3, 1172+ 9,0,0,3, 9,0,1,3, 9,0,2,3, 9,0,3,3, 9,0,4,3, 9,0,5,3, 9,0,6,3, 9,0,7,3, 9,0,8,3, 1173+ 9,0,9,3, 9,1,0,3, 9,1,1,3, 9,1,2,3, 9,1,3,3, 9,1,4,3, 9,1,5,3, 9,1,6,3, 9,1,7,3, 1174+ 9,1,8,3, 9,1,9,3, 9,2,0,3, 9,2,1,3, 9,2,2,3, 9,2,3,3, 9,2,4,3, 9,2,5,3, 9,2,6,3, 1175+ 9,2,7,3, 9,2,8,3, 9,2,9,3, 9,3,0,3, 9,3,1,3, 9,3,2,3, 9,3,3,3, 9,3,4,3, 9,3,5,3, 1176+ 9,3,6,3, 9,3,7,3, 9,3,8,3, 9,3,9,3, 9,4,0,3, 9,4,1,3, 9,4,2,3, 9,4,3,3, 9,4,4,3, 1177+ 9,4,5,3, 9,4,6,3, 9,4,7,3, 9,4,8,3, 9,4,9,3, 9,5,0,3, 9,5,1,3, 9,5,2,3, 9,5,3,3, 1178+ 9,5,4,3, 9,5,5,3, 9,5,6,3, 9,5,7,3, 9,5,8,3, 9,5,9,3, 9,6,0,3, 9,6,1,3, 9,6,2,3, 1179+ 9,6,3,3, 9,6,4,3, 9,6,5,3, 9,6,6,3, 9,6,7,3, 9,6,8,3, 9,6,9,3, 9,7,0,3, 9,7,1,3, 1180+ 9,7,2,3, 9,7,3,3, 9,7,4,3, 9,7,5,3, 9,7,6,3, 9,7,7,3, 9,7,8,3, 9,7,9,3, 9,8,0,3, 1181+ 9,8,1,3, 9,8,2,3, 9,8,3,3, 9,8,4,3, 9,8,5,3, 9,8,6,3, 9,8,7,3, 9,8,8,3, 9,8,9,3, 1182+ 9,9,0,3, 9,9,1,3, 9,9,2,3, 9,9,3,3, 9,9,4,3, 9,9,5,3, 9,9,6,3, 9,9,7,3, 9,9,8,3, 1183+ 9,9,9,3};1184+#endif1185+ added:src/decNumber/decimal128.c+553 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 128-bit format module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for decimal128 format numbers. */20+/* Conversions are supplied to and from decNumber and String. */21+/* */22+/* This is used when decNumber provides operations, either for all */23+/* operations or as a proxy between decNumber and decSingle. */24+/* */25+/* Error handling is the same as decNumber (qv.). */26+/* ------------------------------------------------------------------ */27+#include <string.h> // [for memset/memcpy]28+#include <stdio.h> // [for printf]29+30+#define DECNUMDIGITS 34 // make decNumbers with space for 3431+#include "decNumber.h" // base number library32+#include "decNumberLocal.h" // decNumber local types, etc.33+#include "decimal128.h" // our primary include34+35+/* Utility routines and tables [in decimal64.c] */36+// DPD2BIN and the reverse are renamed to prevent link-time conflict37+// if decQuad is also built in the same executable38+#define DPD2BIN DPD2BINx39+#define BIN2DPD BIN2DPDx40+extern const uInt COMBEXP[32], COMBMSD[32];41+extern const uShort DPD2BIN[1024];42+extern const uShort BIN2DPD[1000]; // [not used]43+extern const uByte BIN2CHAR[4001];44+45+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);46+extern void decDigitsToDPD(const decNumber *, uInt *, Int);47+48+#if DECTRACE || DECCHECK49+void decimal128Show(const decimal128 *); // for debug50+extern void decNumberShow(const decNumber *); // ..51+#endif52+53+/* Useful macro */54+// Clear a structure (e.g., a decNumber)55+#define DEC_clear(d) memset(d, 0, sizeof(*d))56+57+/* ------------------------------------------------------------------ */58+/* decimal128FromNumber -- convert decNumber to decimal128 */59+/* */60+/* ds is the target decimal128 */61+/* dn is the source number (assumed valid) */62+/* set is the context, used only for reporting errors */63+/* */64+/* The set argument is used only for status reporting and for the */65+/* rounding mode (used if the coefficient is more than DECIMAL128_Pmax*/66+/* digits or an overflow is detected). If the exponent is out of the */67+/* valid range then Overflow or Underflow will be raised. */68+/* After Underflow a subnormal result is possible. */69+/* */70+/* DEC_Clamped is set if the number has to be 'folded down' to fit, */71+/* by reducing its exponent and multiplying the coefficient by a */72+/* power of ten, or if the exponent on a zero had to be clamped. */73+/* ------------------------------------------------------------------ */74+decimal128 * decimal128FromNumber(decimal128 *d128, const decNumber *dn,75+ decContext *set) {76+ uInt status=0; // status accumulator77+ Int ae; // adjusted exponent78+ decNumber dw; // work79+ decContext dc; // ..80+ uInt comb, exp; // ..81+ uInt uiwork; // for macros82+ uInt targar[4]={0,0,0,0}; // target 128-bit83+ #define targhi targar[3] // name the word with the sign84+ #define targmh targar[2] // name the words85+ #define targml targar[1] // ..86+ #define targlo targar[0] // ..87+88+ // If the number has too many digits, or the exponent could be89+ // out of range then reduce the number under the appropriate90+ // constraints. This could push the number to Infinity or zero,91+ // so this check and rounding must be done before generating the92+ // decimal128]93+ ae=dn->exponent+dn->digits-1; // [0 if special]94+ if (dn->digits>DECIMAL128_Pmax // too many digits95+ || ae>DECIMAL128_Emax // likely overflow96+ || ae<DECIMAL128_Emin) { // likely underflow97+ decContextDefault(&dc, DEC_INIT_DECIMAL128); // [no traps]98+ dc.round=set->round; // use supplied rounding99+ decNumberPlus(&dw, dn, &dc); // (round and check)100+ // [this changes -0 to 0, so enforce the sign...]101+ dw.bits|=dn->bits&DECNEG;102+ status=dc.status; // save status103+ dn=&dw; // use the work number104+ } // maybe out of range105+106+ if (dn->bits&DECSPECIAL) { // a special value107+ if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;108+ else { // sNaN or qNaN109+ if ((*dn->lsu!=0 || dn->digits>1) // non-zero coefficient110+ && (dn->digits<DECIMAL128_Pmax)) { // coefficient fits111+ decDigitsToDPD(dn, targar, 0);112+ }113+ if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;114+ else targhi|=DECIMAL_sNaN<<24;115+ } // a NaN116+ } // special117+118+ else { // is finite119+ if (decNumberIsZero(dn)) { // is a zero120+ // set and clamp exponent121+ if (dn->exponent<-DECIMAL128_Bias) {122+ exp=0; // low clamp123+ status|=DEC_Clamped;124+ }125+ else {126+ exp=dn->exponent+DECIMAL128_Bias; // bias exponent127+ if (exp>DECIMAL128_Ehigh) { // top clamp128+ exp=DECIMAL128_Ehigh;129+ status|=DEC_Clamped;130+ }131+ }132+ comb=(exp>>9) & 0x18; // msd=0, exp top 2 bits ..133+ }134+ else { // non-zero finite number135+ uInt msd; // work136+ Int pad=0; // coefficient pad digits137+138+ // the dn is known to fit, but it may need to be padded139+ exp=(uInt)(dn->exponent+DECIMAL128_Bias); // bias exponent140+ if (exp>DECIMAL128_Ehigh) { // fold-down case141+ pad=exp-DECIMAL128_Ehigh;142+ exp=DECIMAL128_Ehigh; // [to maximum]143+ status|=DEC_Clamped;144+ }145+146+ // [fastpath for common case is not a win, here]147+ decDigitsToDPD(dn, targar, pad);148+ // save and clear the top digit149+ msd=targhi>>14;150+ targhi&=0x00003fff;151+152+ // create the combination field153+ if (msd>=8) comb=0x18 | ((exp>>11) & 0x06) | (msd & 0x01);154+ else comb=((exp>>9) & 0x18) | msd;155+ }156+ targhi|=comb<<26; // add combination field ..157+ targhi|=(exp&0xfff)<<14; // .. and exponent continuation158+ } // finite159+160+ if (dn->bits&DECNEG) targhi|=0x80000000; // add sign bit161+162+ // now write to storage; this is endian163+ if (DECLITEND) {164+ // lo -> hi165+ UBFROMUI(d128->bytes, targlo);166+ UBFROMUI(d128->bytes+4, targml);167+ UBFROMUI(d128->bytes+8, targmh);168+ UBFROMUI(d128->bytes+12, targhi);169+ }170+ else {171+ // hi -> lo172+ UBFROMUI(d128->bytes, targhi);173+ UBFROMUI(d128->bytes+4, targmh);174+ UBFROMUI(d128->bytes+8, targml);175+ UBFROMUI(d128->bytes+12, targlo);176+ }177+178+ if (status!=0) decContextSetStatus(set, status); // pass on status179+ // decimal128Show(d128);180+ return d128;181+ } // decimal128FromNumber182+183+/* ------------------------------------------------------------------ */184+/* decimal128ToNumber -- convert decimal128 to decNumber */185+/* d128 is the source decimal128 */186+/* dn is the target number, with appropriate space */187+/* No error is possible. */188+/* ------------------------------------------------------------------ */189+decNumber * decimal128ToNumber(const decimal128 *d128, decNumber *dn) {190+ uInt msd; // coefficient MSD191+ uInt exp; // exponent top two bits192+ uInt comb; // combination field193+ Int need; // work194+ uInt uiwork; // for macros195+ uInt sourar[4]; // source 128-bit196+ #define sourhi sourar[3] // name the word with the sign197+ #define sourmh sourar[2] // and the mid-high word198+ #define sourml sourar[1] // and the mod-low word199+ #define sourlo sourar[0] // and the lowest word200+201+ // load source from storage; this is endian202+ if (DECLITEND) {203+ sourlo=UBTOUI(d128->bytes ); // directly load the low int204+ sourml=UBTOUI(d128->bytes+4 ); // then the mid-low205+ sourmh=UBTOUI(d128->bytes+8 ); // then the mid-high206+ sourhi=UBTOUI(d128->bytes+12); // then the high int207+ }208+ else {209+ sourhi=UBTOUI(d128->bytes ); // directly load the high int210+ sourmh=UBTOUI(d128->bytes+4 ); // then the mid-high211+ sourml=UBTOUI(d128->bytes+8 ); // then the mid-low212+ sourlo=UBTOUI(d128->bytes+12); // then the low int213+ }214+215+ comb=(sourhi>>26)&0x1f; // combination field216+217+ decNumberZero(dn); // clean number218+ if (sourhi&0x80000000) dn->bits=DECNEG; // set sign if negative219+220+ msd=COMBMSD[comb]; // decode the combination field221+ exp=COMBEXP[comb]; // ..222+223+ if (exp==3) { // is a special224+ if (msd==0) {225+ dn->bits|=DECINF;226+ return dn; // no coefficient needed227+ }228+ else if (sourhi&0x02000000) dn->bits|=DECSNAN;229+ else dn->bits|=DECNAN;230+ msd=0; // no top digit231+ }232+ else { // is a finite number233+ dn->exponent=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; // unbiased234+ }235+236+ // get the coefficient237+ sourhi&=0x00003fff; // clean coefficient continuation238+ if (msd) { // non-zero msd239+ sourhi|=msd<<14; // prefix to coefficient240+ need=12; // process 12 declets241+ }242+ else { // msd=0243+ if (sourhi) need=11; // declets to process244+ else if (sourmh) need=10;245+ else if (sourml) need=7;246+ else if (sourlo) need=4;247+ else return dn; // easy: coefficient is 0248+ } //msd=0249+250+ decDigitsFromDPD(dn, sourar, need); // process declets251+ // decNumberShow(dn);252+ return dn;253+ } // decimal128ToNumber254+255+/* ------------------------------------------------------------------ */256+/* to-scientific-string -- conversion to numeric string */257+/* to-engineering-string -- conversion to numeric string */258+/* */259+/* decimal128ToString(d128, string); */260+/* decimal128ToEngString(d128, string); */261+/* */262+/* d128 is the decimal128 format number to convert */263+/* string is the string where the result will be laid out */264+/* */265+/* string must be at least 24 characters */266+/* */267+/* No error is possible, and no status can be set. */268+/* ------------------------------------------------------------------ */269+char * decimal128ToEngString(const decimal128 *d128, char *string){270+ decNumber dn; // work271+ decimal128ToNumber(d128, &dn);272+ decNumberToEngString(&dn, string);273+ return string;274+ } // decimal128ToEngString275+276+char * decimal128ToString(const decimal128 *d128, char *string){277+ uInt msd; // coefficient MSD278+ Int exp; // exponent top two bits or full279+ uInt comb; // combination field280+ char *cstart; // coefficient start281+ char *c; // output pointer in string282+ const uByte *u; // work283+ char *s, *t; // .. (source, target)284+ Int dpd; // ..285+ Int pre, e; // ..286+ uInt uiwork; // for macros287+288+ uInt sourar[4]; // source 128-bit289+ #define sourhi sourar[3] // name the word with the sign290+ #define sourmh sourar[2] // and the mid-high word291+ #define sourml sourar[1] // and the mod-low word292+ #define sourlo sourar[0] // and the lowest word293+294+ // load source from storage; this is endian295+ if (DECLITEND) {296+ sourlo=UBTOUI(d128->bytes ); // directly load the low int297+ sourml=UBTOUI(d128->bytes+4 ); // then the mid-low298+ sourmh=UBTOUI(d128->bytes+8 ); // then the mid-high299+ sourhi=UBTOUI(d128->bytes+12); // then the high int300+ }301+ else {302+ sourhi=UBTOUI(d128->bytes ); // directly load the high int303+ sourmh=UBTOUI(d128->bytes+4 ); // then the mid-high304+ sourml=UBTOUI(d128->bytes+8 ); // then the mid-low305+ sourlo=UBTOUI(d128->bytes+12); // then the low int306+ }307+308+ c=string; // where result will go309+ if (((Int)sourhi)<0) *c++='-'; // handle sign310+311+ comb=(sourhi>>26)&0x1f; // combination field312+ msd=COMBMSD[comb]; // decode the combination field313+ exp=COMBEXP[comb]; // ..314+315+ if (exp==3) {316+ if (msd==0) { // infinity317+ strcpy(c, "Inf");318+ strcpy(c+3, "inity");319+ return string; // easy320+ }321+ if (sourhi&0x02000000) *c++='s'; // sNaN322+ strcpy(c, "NaN"); // complete word323+ c+=3; // step past324+ if (sourlo==0 && sourml==0 && sourmh==0325+ && (sourhi&0x0003ffff)==0) return string; // zero payload326+ // otherwise drop through to add integer; set correct exp327+ exp=0; msd=0; // setup for following code328+ }329+ else exp=(exp<<12)+((sourhi>>14)&0xfff)-DECIMAL128_Bias; // unbiased330+331+ // convert 34 digits of significand to characters332+ cstart=c; // save start of coefficient333+ if (msd) *c++='0'+(char)msd; // non-zero most significant digit334+335+ // Now decode the declets. After extracting each one, it is336+ // decoded to binary and then to a 4-char sequence by table lookup;337+ // the 4-chars are a 1-char length (significant digits, except 000338+ // has length 0). This allows us to left-align the first declet339+ // with non-zero content, then remaining ones are full 3-char340+ // length. We use fixed-length memcpys because variable-length341+ // causes a subroutine call in GCC. (These are length 4 for speed342+ // and are safe because the array has an extra terminator byte.)343+ #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; \344+ if (c!=cstart) {memcpy(c, u+1, 4); c+=3;} \345+ else if (*u) {memcpy(c, u+4-*u, 4); c+=*u;}346+ dpd=(sourhi>>4)&0x3ff; // declet 1347+ dpd2char;348+ dpd=((sourhi&0xf)<<6) | (sourmh>>26); // declet 2349+ dpd2char;350+ dpd=(sourmh>>16)&0x3ff; // declet 3351+ dpd2char;352+ dpd=(sourmh>>6)&0x3ff; // declet 4353+ dpd2char;354+ dpd=((sourmh&0x3f)<<4) | (sourml>>28); // declet 5355+ dpd2char;356+ dpd=(sourml>>18)&0x3ff; // declet 6357+ dpd2char;358+ dpd=(sourml>>8)&0x3ff; // declet 7359+ dpd2char;360+ dpd=((sourml&0xff)<<2) | (sourlo>>30); // declet 8361+ dpd2char;362+ dpd=(sourlo>>20)&0x3ff; // declet 9363+ dpd2char;364+ dpd=(sourlo>>10)&0x3ff; // declet 10365+ dpd2char;366+ dpd=(sourlo)&0x3ff; // declet 11367+ dpd2char;368+369+ if (c==cstart) *c++='0'; // all zeros -- make 0370+371+ if (exp==0) { // integer or NaN case -- easy372+ *c='\0'; // terminate373+ return string;374+ }375+376+ /* non-0 exponent */377+ e=0; // assume no E378+ pre=c-cstart+exp;379+ // [here, pre-exp is the digits count (==1 for zero)]380+ if (exp>0 || pre<-5) { // need exponential form381+ e=pre-1; // calculate E value382+ pre=1; // assume one digit before '.'383+ } // exponential form384+385+ /* modify the coefficient, adding 0s, '.', and E+nn as needed */386+ s=c-1; // source (LSD)387+ if (pre>0) { // ddd.ddd (plain), perhaps with E388+ char *dotat=cstart+pre;389+ if (dotat<c) { // if embedded dot needed...390+ t=c; // target391+ for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap392+ *t='.'; // insert the dot393+ c++; // length increased by one394+ }395+396+ // finally add the E-part, if needed; it will never be 0, and has397+ // a maximum length of 4 digits398+ if (e!=0) {399+ *c++='E'; // starts with E400+ *c++='+'; // assume positive401+ if (e<0) {402+ *(c-1)='-'; // oops, need '-'403+ e=-e; // uInt, please404+ }405+ if (e<1000) { // 3 (or fewer) digits case406+ u=&BIN2CHAR[e*4]; // -> length byte407+ memcpy(c, u+4-*u, 4); // copy fixed 4 characters [is safe]408+ c+=*u; // bump pointer appropriately409+ }410+ else { // 4-digits411+ Int thou=((e>>3)*1049)>>17; // e/1000412+ Int rem=e-(1000*thou); // e%1000413+ *c++='0'+(char)thou;414+ u=&BIN2CHAR[rem*4]; // -> length byte415+ memcpy(c, u+1, 4); // copy fixed 3+1 characters [is safe]416+ c+=3; // bump pointer, always 3 digits417+ }418+ }419+ *c='\0'; // add terminator420+ //printf("res %s\n", string);421+ return string;422+ } // pre>0423+424+ /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */425+ t=c+1-pre;426+ *(t+1)='\0'; // can add terminator now427+ for (; s>=cstart; s--, t--) *t=*s; // shift whole coefficient right428+ c=cstart;429+ *c++='0'; // always starts with 0.430+ *c++='.';431+ for (; pre<0; pre++) *c++='0'; // add any 0's after '.'432+ //printf("res %s\n", string);433+ return string;434+ } // decimal128ToString435+436+/* ------------------------------------------------------------------ */437+/* to-number -- conversion from numeric string */438+/* */439+/* decimal128FromString(result, string, set); */440+/* */441+/* result is the decimal128 format number which gets the result of */442+/* the conversion */443+/* *string is the character string which should contain a valid */444+/* number (which may be a special value) */445+/* set is the context */446+/* */447+/* The context is supplied to this routine is used for error handling */448+/* (setting of status and traps) and for the rounding mode, only. */449+/* If an error occurs, the result will be a valid decimal128 NaN. */450+/* ------------------------------------------------------------------ */451+decimal128 * decimal128FromString(decimal128 *result, const char *string,452+ decContext *set) {453+ decContext dc; // work454+ decNumber dn; // ..455+456+ decContextDefault(&dc, DEC_INIT_DECIMAL128); // no traps, please457+ dc.round=set->round; // use supplied rounding458+459+ decNumberFromString(&dn, string, &dc); // will round if needed460+ decimal128FromNumber(result, &dn, &dc);461+ if (dc.status!=0) { // something happened462+ decContextSetStatus(set, dc.status); // .. pass it on463+ }464+ return result;465+ } // decimal128FromString466+467+/* ------------------------------------------------------------------ */468+/* decimal128IsCanonical -- test whether encoding is canonical */469+/* d128 is the source decimal128 */470+/* returns 1 if the encoding of d128 is canonical, 0 otherwise */471+/* No error is possible. */472+/* ------------------------------------------------------------------ */473+uInt decimal128IsCanonical(const decimal128 *d128) {474+ decNumber dn; // work475+ decimal128 canon; // ..476+ decContext dc; // ..477+ decContextDefault(&dc, DEC_INIT_DECIMAL128);478+ decimal128ToNumber(d128, &dn);479+ decimal128FromNumber(&canon, &dn, &dc);// canon will now be canonical480+ return memcmp(d128, &canon, DECIMAL128_Bytes)==0;481+ } // decimal128IsCanonical482+483+/* ------------------------------------------------------------------ */484+/* decimal128Canonical -- copy an encoding, ensuring it is canonical */485+/* d128 is the source decimal128 */486+/* result is the target (may be the same decimal128) */487+/* returns result */488+/* No error is possible. */489+/* ------------------------------------------------------------------ */490+decimal128 * decimal128Canonical(decimal128 *result, const decimal128 *d128) {491+ decNumber dn; // work492+ decContext dc; // ..493+ decContextDefault(&dc, DEC_INIT_DECIMAL128);494+ decimal128ToNumber(d128, &dn);495+ decimal128FromNumber(result, &dn, &dc);// result will now be canonical496+ return result;497+ } // decimal128Canonical498+499+#if DECTRACE || DECCHECK500+/* Macros for accessing decimal128 fields. These assume the argument501+ is a reference (pointer) to the decimal128 structure, and the502+ decimal128 is in network byte order (big-endian) */503+// Get sign504+#define decimal128Sign(d) ((unsigned)(d)->bytes[0]>>7)505+506+// Get combination field507+#define decimal128Comb(d) (((d)->bytes[0] & 0x7c)>>2)508+509+// Get exponent continuation [does not remove bias]510+#define decimal128ExpCon(d) ((((d)->bytes[0] & 0x03)<<10) \511+ | ((unsigned)(d)->bytes[1]<<2) \512+ | ((unsigned)(d)->bytes[2]>>6))513+514+// Set sign [this assumes sign previously 0]515+#define decimal128SetSign(d, b) { \516+ (d)->bytes[0]|=((unsigned)(b)<<7);}517+518+// Set exponent continuation [does not apply bias]519+// This assumes range has been checked and exponent previously 0;520+// type of exponent must be unsigned521+#define decimal128SetExpCon(d, e) { \522+ (d)->bytes[0]|=(uByte)((e)>>10); \523+ (d)->bytes[1] =(uByte)(((e)&0x3fc)>>2); \524+ (d)->bytes[2]|=(uByte)(((e)&0x03)<<6);}525+526+/* ------------------------------------------------------------------ */527+/* decimal128Show -- display a decimal128 in hexadecimal [debug aid] */528+/* d128 -- the number to show */529+/* ------------------------------------------------------------------ */530+// Also shows sign/cob/expconfields extracted531+void decimal128Show(const decimal128 *d128) {532+ char buf[DECIMAL128_Bytes*2+1];533+ Int i, j=0;534+535+ if (DECLITEND) {536+ for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {537+ sprintf(&buf[j], "%02x", d128->bytes[15-i]);538+ }539+ printf(" D128> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,540+ d128->bytes[15]>>7, (d128->bytes[15]>>2)&0x1f,541+ ((d128->bytes[15]&0x3)<<10)|(d128->bytes[14]<<2)|542+ (d128->bytes[13]>>6));543+ }544+ else {545+ for (i=0; i<DECIMAL128_Bytes; i++, j+=2) {546+ sprintf(&buf[j], "%02x", d128->bytes[i]);547+ }548+ printf(" D128> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,549+ decimal128Sign(d128), decimal128Comb(d128),550+ decimal128ExpCon(d128));551+ }552+ } // decimal128Show553+#endifadded:src/decNumber/decimal128.h+81 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 128-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2005. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECIMAL128)21+ #define DECIMAL12822+ #define DEC128NAME "decimal128" /* Short name */23+ #define DEC128FULLNAME "Decimal 128-bit Number" /* Verbose name */24+ #define DEC128AUTHOR "Mike Cowlishaw" /* Who to blame */25+26+ /* parameters for decimal128s */27+ #define DECIMAL128_Bytes 16 /* length */28+ #define DECIMAL128_Pmax 34 /* maximum precision (digits) */29+ #define DECIMAL128_Emax 6144 /* maximum adjusted exponent */30+ #define DECIMAL128_Emin -6143 /* minimum adjusted exponent */31+ #define DECIMAL128_Bias 6176 /* bias for the exponent */32+ #define DECIMAL128_String 43 /* maximum string length, +1 */33+ #define DECIMAL128_EconL 12 /* exp. continuation length */34+ /* highest biased exponent (Elimit-1) */35+ #define DECIMAL128_Ehigh (DECIMAL128_Emax+DECIMAL128_Bias-DECIMAL128_Pmax+1)36+37+ /* check enough digits, if pre-defined */38+ #if defined(DECNUMDIGITS)39+ #if (DECNUMDIGITS<DECIMAL128_Pmax)40+ #error decimal128.h needs pre-defined DECNUMDIGITS>=34 for safe use41+ #endif42+ #endif43+44+ #ifndef DECNUMDIGITS45+ #define DECNUMDIGITS DECIMAL128_Pmax /* size if not already defined*/46+ #endif47+ #ifndef DECNUMBER48+ #include "decNumber.h" /* context and number library */49+ #endif50+51+ /* Decimal 128-bit type, accessible by bytes */52+ typedef struct {53+ uint8_t bytes[DECIMAL128_Bytes]; /* decimal128: 1, 5, 12, 110 bits*/54+ } decimal128;55+56+ /* special values [top byte excluding sign bit; last two bits are */57+ /* don't-care for Infinity on input, last bit don't-care for NaN] */58+ #if !defined(DECIMAL_NaN)59+ #define DECIMAL_NaN 0x7c /* 0 11111 00 NaN */60+ #define DECIMAL_sNaN 0x7e /* 0 11111 10 sNaN */61+ #define DECIMAL_Inf 0x78 /* 0 11110 00 Infinity */62+ #endif63+64+ /* ---------------------------------------------------------------- */65+ /* Routines */66+ /* ---------------------------------------------------------------- */67+ /* String conversions */68+ decimal128 * decimal128FromString(decimal128 *, const char *, decContext *);69+ char * decimal128ToString(const decimal128 *, char *);70+ char * decimal128ToEngString(const decimal128 *, char *);71+72+ /* decNumber conversions */73+ decimal128 * decimal128FromNumber(decimal128 *, const decNumber *,74+ decContext *);75+ decNumber * decimal128ToNumber(const decimal128 *, decNumber *);76+77+ /* Format-dependent utilities */78+ uint32_t decimal128IsCanonical(const decimal128 *);79+ decimal128 * decimal128Canonical(decimal128 *, const decimal128 *);80+81+#endifadded:src/decNumber/decimal32.c+476 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 32-bit format module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for decimal32 format numbers. */20+/* Conversions are supplied to and from decNumber and String. */21+/* */22+/* This is used when decNumber provides operations, either for all */23+/* operations or as a proxy between decNumber and decSingle. */24+/* */25+/* Error handling is the same as decNumber (qv.). */26+/* ------------------------------------------------------------------ */27+#include <string.h> // [for memset/memcpy]28+#include <stdio.h> // [for printf]29+30+#define DECNUMDIGITS 7 // make decNumbers with space for 731+#include "decNumber.h" // base number library32+#include "decNumberLocal.h" // decNumber local types, etc.33+#include "decimal32.h" // our primary include34+35+/* Utility tables and routines [in decimal64.c] */36+// DPD2BIN and the reverse are renamed to prevent link-time conflict37+// if decQuad is also built in the same executable38+#define DPD2BIN DPD2BINx39+#define BIN2DPD BIN2DPDx40+extern const uInt COMBEXP[32], COMBMSD[32];41+extern const uShort DPD2BIN[1024];42+extern const uShort BIN2DPD[1000];43+extern const uByte BIN2CHAR[4001];44+45+extern void decDigitsToDPD(const decNumber *, uInt *, Int);46+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);47+48+#if DECTRACE || DECCHECK49+void decimal32Show(const decimal32 *); // for debug50+extern void decNumberShow(const decNumber *); // ..51+#endif52+53+/* Useful macro */54+// Clear a structure (e.g., a decNumber)55+#define DEC_clear(d) memset(d, 0, sizeof(*d))56+57+/* ------------------------------------------------------------------ */58+/* decimal32FromNumber -- convert decNumber to decimal32 */59+/* */60+/* ds is the target decimal32 */61+/* dn is the source number (assumed valid) */62+/* set is the context, used only for reporting errors */63+/* */64+/* The set argument is used only for status reporting and for the */65+/* rounding mode (used if the coefficient is more than DECIMAL32_Pmax */66+/* digits or an overflow is detected). If the exponent is out of the */67+/* valid range then Overflow or Underflow will be raised. */68+/* After Underflow a subnormal result is possible. */69+/* */70+/* DEC_Clamped is set if the number has to be 'folded down' to fit, */71+/* by reducing its exponent and multiplying the coefficient by a */72+/* power of ten, or if the exponent on a zero had to be clamped. */73+/* ------------------------------------------------------------------ */74+decimal32 * decimal32FromNumber(decimal32 *d32, const decNumber *dn,75+ decContext *set) {76+ uInt status=0; // status accumulator77+ Int ae; // adjusted exponent78+ decNumber dw; // work79+ decContext dc; // ..80+ uInt comb, exp; // ..81+ uInt uiwork; // for macros82+ uInt targ=0; // target 32-bit83+84+ // If the number has too many digits, or the exponent could be85+ // out of range then reduce the number under the appropriate86+ // constraints. This could push the number to Infinity or zero,87+ // so this check and rounding must be done before generating the88+ // decimal32]89+ ae=dn->exponent+dn->digits-1; // [0 if special]90+ if (dn->digits>DECIMAL32_Pmax // too many digits91+ || ae>DECIMAL32_Emax // likely overflow92+ || ae<DECIMAL32_Emin) { // likely underflow93+ decContextDefault(&dc, DEC_INIT_DECIMAL32); // [no traps]94+ dc.round=set->round; // use supplied rounding95+ decNumberPlus(&dw, dn, &dc); // (round and check)96+ // [this changes -0 to 0, so enforce the sign...]97+ dw.bits|=dn->bits&DECNEG;98+ status=dc.status; // save status99+ dn=&dw; // use the work number100+ } // maybe out of range101+102+ if (dn->bits&DECSPECIAL) { // a special value103+ if (dn->bits&DECINF) targ=DECIMAL_Inf<<24;104+ else { // sNaN or qNaN105+ if ((*dn->lsu!=0 || dn->digits>1) // non-zero coefficient106+ && (dn->digits<DECIMAL32_Pmax)) { // coefficient fits107+ decDigitsToDPD(dn, &targ, 0);108+ }109+ if (dn->bits&DECNAN) targ|=DECIMAL_NaN<<24;110+ else targ|=DECIMAL_sNaN<<24;111+ } // a NaN112+ } // special113+114+ else { // is finite115+ if (decNumberIsZero(dn)) { // is a zero116+ // set and clamp exponent117+ if (dn->exponent<-DECIMAL32_Bias) {118+ exp=0; // low clamp119+ status|=DEC_Clamped;120+ }121+ else {122+ exp=dn->exponent+DECIMAL32_Bias; // bias exponent123+ if (exp>DECIMAL32_Ehigh) { // top clamp124+ exp=DECIMAL32_Ehigh;125+ status|=DEC_Clamped;126+ }127+ }128+ comb=(exp>>3) & 0x18; // msd=0, exp top 2 bits ..129+ }130+ else { // non-zero finite number131+ uInt msd; // work132+ Int pad=0; // coefficient pad digits133+134+ // the dn is known to fit, but it may need to be padded135+ exp=(uInt)(dn->exponent+DECIMAL32_Bias); // bias exponent136+ if (exp>DECIMAL32_Ehigh) { // fold-down case137+ pad=exp-DECIMAL32_Ehigh;138+ exp=DECIMAL32_Ehigh; // [to maximum]139+ status|=DEC_Clamped;140+ }141+142+ // fastpath common case143+ if (DECDPUN==3 && pad==0) {144+ targ=BIN2DPD[dn->lsu[0]];145+ if (dn->digits>3) targ|=(uInt)(BIN2DPD[dn->lsu[1]])<<10;146+ msd=(dn->digits==7 ? dn->lsu[2] : 0);147+ }148+ else { // general case149+ decDigitsToDPD(dn, &targ, pad);150+ // save and clear the top digit151+ msd=targ>>20;152+ targ&=0x000fffff;153+ }154+155+ // create the combination field156+ if (msd>=8) comb=0x18 | ((exp>>5) & 0x06) | (msd & 0x01);157+ else comb=((exp>>3) & 0x18) | msd;158+ }159+ targ|=comb<<26; // add combination field ..160+ targ|=(exp&0x3f)<<20; // .. and exponent continuation161+ } // finite162+163+ if (dn->bits&DECNEG) targ|=0x80000000; // add sign bit164+165+ // now write to storage; this is endian166+ UBFROMUI(d32->bytes, targ); // directly store the int167+168+ if (status!=0) decContextSetStatus(set, status); // pass on status169+ // decimal32Show(d32);170+ return d32;171+ } // decimal32FromNumber172+173+/* ------------------------------------------------------------------ */174+/* decimal32ToNumber -- convert decimal32 to decNumber */175+/* d32 is the source decimal32 */176+/* dn is the target number, with appropriate space */177+/* No error is possible. */178+/* ------------------------------------------------------------------ */179+decNumber * decimal32ToNumber(const decimal32 *d32, decNumber *dn) {180+ uInt msd; // coefficient MSD181+ uInt exp; // exponent top two bits182+ uInt comb; // combination field183+ uInt sour; // source 32-bit184+ uInt uiwork; // for macros185+186+ // load source from storage; this is endian187+ sour=UBTOUI(d32->bytes); // directly load the int188+189+ comb=(sour>>26)&0x1f; // combination field190+191+ decNumberZero(dn); // clean number192+ if (sour&0x80000000) dn->bits=DECNEG; // set sign if negative193+194+ msd=COMBMSD[comb]; // decode the combination field195+ exp=COMBEXP[comb]; // ..196+197+ if (exp==3) { // is a special198+ if (msd==0) {199+ dn->bits|=DECINF;200+ return dn; // no coefficient needed201+ }202+ else if (sour&0x02000000) dn->bits|=DECSNAN;203+ else dn->bits|=DECNAN;204+ msd=0; // no top digit205+ }206+ else { // is a finite number207+ dn->exponent=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased208+ }209+210+ // get the coefficient211+ sour&=0x000fffff; // clean coefficient continuation212+ if (msd) { // non-zero msd213+ sour|=msd<<20; // prefix to coefficient214+ decDigitsFromDPD(dn, &sour, 3); // process 3 declets215+ return dn;216+ }217+ // msd=0218+ if (!sour) return dn; // easy: coefficient is 0219+ if (sour&0x000ffc00) // need 2 declets?220+ decDigitsFromDPD(dn, &sour, 2); // process 2 declets221+ else222+ decDigitsFromDPD(dn, &sour, 1); // process 1 declet223+ return dn;224+ } // decimal32ToNumber225+226+/* ------------------------------------------------------------------ */227+/* to-scientific-string -- conversion to numeric string */228+/* to-engineering-string -- conversion to numeric string */229+/* */230+/* decimal32ToString(d32, string); */231+/* decimal32ToEngString(d32, string); */232+/* */233+/* d32 is the decimal32 format number to convert */234+/* string is the string where the result will be laid out */235+/* */236+/* string must be at least 24 characters */237+/* */238+/* No error is possible, and no status can be set. */239+/* ------------------------------------------------------------------ */240+char * decimal32ToEngString(const decimal32 *d32, char *string){241+ decNumber dn; // work242+ decimal32ToNumber(d32, &dn);243+ decNumberToEngString(&dn, string);244+ return string;245+ } // decimal32ToEngString246+247+char * decimal32ToString(const decimal32 *d32, char *string){248+ uInt msd; // coefficient MSD249+ Int exp; // exponent top two bits or full250+ uInt comb; // combination field251+ char *cstart; // coefficient start252+ char *c; // output pointer in string253+ const uByte *u; // work254+ char *s, *t; // .. (source, target)255+ Int dpd; // ..256+ Int pre, e; // ..257+ uInt uiwork; // for macros258+ uInt sour; // source 32-bit259+260+ // load source from storage; this is endian261+ sour=UBTOUI(d32->bytes); // directly load the int262+263+ c=string; // where result will go264+ if (((Int)sour)<0) *c++='-'; // handle sign265+266+ comb=(sour>>26)&0x1f; // combination field267+ msd=COMBMSD[comb]; // decode the combination field268+ exp=COMBEXP[comb]; // ..269+270+ if (exp==3) {271+ if (msd==0) { // infinity272+ strcpy(c, "Inf");273+ strcpy(c+3, "inity");274+ return string; // easy275+ }276+ if (sour&0x02000000) *c++='s'; // sNaN277+ strcpy(c, "NaN"); // complete word278+ c+=3; // step past279+ if ((sour&0x000fffff)==0) return string; // zero payload280+ // otherwise drop through to add integer; set correct exp281+ exp=0; msd=0; // setup for following code282+ }283+ else exp=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased284+285+ // convert 7 digits of significand to characters286+ cstart=c; // save start of coefficient287+ if (msd) *c++='0'+(char)msd; // non-zero most significant digit288+289+ // Now decode the declets. After extracting each one, it is290+ // decoded to binary and then to a 4-char sequence by table lookup;291+ // the 4-chars are a 1-char length (significant digits, except 000292+ // has length 0). This allows us to left-align the first declet293+ // with non-zero content, then remaining ones are full 3-char294+ // length. We use fixed-length memcpys because variable-length295+ // causes a subroutine call in GCC. (These are length 4 for speed296+ // and are safe because the array has an extra terminator byte.)297+ #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; \298+ if (c!=cstart) {memcpy(c, u+1, 4); c+=3;} \299+ else if (*u) {memcpy(c, u+4-*u, 4); c+=*u;}300+301+ dpd=(sour>>10)&0x3ff; // declet 1302+ dpd2char;303+ dpd=(sour)&0x3ff; // declet 2304+ dpd2char;305+306+ if (c==cstart) *c++='0'; // all zeros -- make 0307+308+ if (exp==0) { // integer or NaN case -- easy309+ *c='\0'; // terminate310+ return string;311+ }312+313+ /* non-0 exponent */314+ e=0; // assume no E315+ pre=c-cstart+exp;316+ // [here, pre-exp is the digits count (==1 for zero)]317+ if (exp>0 || pre<-5) { // need exponential form318+ e=pre-1; // calculate E value319+ pre=1; // assume one digit before '.'320+ } // exponential form321+322+ /* modify the coefficient, adding 0s, '.', and E+nn as needed */323+ s=c-1; // source (LSD)324+ if (pre>0) { // ddd.ddd (plain), perhaps with E325+ char *dotat=cstart+pre;326+ if (dotat<c) { // if embedded dot needed...327+ t=c; // target328+ for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap329+ *t='.'; // insert the dot330+ c++; // length increased by one331+ }332+333+ // finally add the E-part, if needed; it will never be 0, and has334+ // a maximum length of 3 digits (E-101 case)335+ if (e!=0) {336+ *c++='E'; // starts with E337+ *c++='+'; // assume positive338+ if (e<0) {339+ *(c-1)='-'; // oops, need '-'340+ e=-e; // uInt, please341+ }342+ u=&BIN2CHAR[e*4]; // -> length byte343+ memcpy(c, u+4-*u, 4); // copy fixed 4 characters [is safe]344+ c+=*u; // bump pointer appropriately345+ }346+ *c='\0'; // add terminator347+ //printf("res %s\n", string);348+ return string;349+ } // pre>0350+351+ /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */352+ t=c+1-pre;353+ *(t+1)='\0'; // can add terminator now354+ for (; s>=cstart; s--, t--) *t=*s; // shift whole coefficient right355+ c=cstart;356+ *c++='0'; // always starts with 0.357+ *c++='.';358+ for (; pre<0; pre++) *c++='0'; // add any 0's after '.'359+ //printf("res %s\n", string);360+ return string;361+ } // decimal32ToString362+363+/* ------------------------------------------------------------------ */364+/* to-number -- conversion from numeric string */365+/* */366+/* decimal32FromString(result, string, set); */367+/* */368+/* result is the decimal32 format number which gets the result of */369+/* the conversion */370+/* *string is the character string which should contain a valid */371+/* number (which may be a special value) */372+/* set is the context */373+/* */374+/* The context is supplied to this routine is used for error handling */375+/* (setting of status and traps) and for the rounding mode, only. */376+/* If an error occurs, the result will be a valid decimal32 NaN. */377+/* ------------------------------------------------------------------ */378+decimal32 * decimal32FromString(decimal32 *result, const char *string,379+ decContext *set) {380+ decContext dc; // work381+ decNumber dn; // ..382+383+ decContextDefault(&dc, DEC_INIT_DECIMAL32); // no traps, please384+ dc.round=set->round; // use supplied rounding385+386+ decNumberFromString(&dn, string, &dc); // will round if needed387+ decimal32FromNumber(result, &dn, &dc);388+ if (dc.status!=0) { // something happened389+ decContextSetStatus(set, dc.status); // .. pass it on390+ }391+ return result;392+ } // decimal32FromString393+394+/* ------------------------------------------------------------------ */395+/* decimal32IsCanonical -- test whether encoding is canonical */396+/* d32 is the source decimal32 */397+/* returns 1 if the encoding of d32 is canonical, 0 otherwise */398+/* No error is possible. */399+/* ------------------------------------------------------------------ */400+uInt decimal32IsCanonical(const decimal32 *d32) {401+ decNumber dn; // work402+ decimal32 canon; // ..403+ decContext dc; // ..404+ decContextDefault(&dc, DEC_INIT_DECIMAL32);405+ decimal32ToNumber(d32, &dn);406+ decimal32FromNumber(&canon, &dn, &dc);// canon will now be canonical407+ return memcmp(d32, &canon, DECIMAL32_Bytes)==0;408+ } // decimal32IsCanonical409+410+/* ------------------------------------------------------------------ */411+/* decimal32Canonical -- copy an encoding, ensuring it is canonical */412+/* d32 is the source decimal32 */413+/* result is the target (may be the same decimal32) */414+/* returns result */415+/* No error is possible. */416+/* ------------------------------------------------------------------ */417+decimal32 * decimal32Canonical(decimal32 *result, const decimal32 *d32) {418+ decNumber dn; // work419+ decContext dc; // ..420+ decContextDefault(&dc, DEC_INIT_DECIMAL32);421+ decimal32ToNumber(d32, &dn);422+ decimal32FromNumber(result, &dn, &dc);// result will now be canonical423+ return result;424+ } // decimal32Canonical425+426+#if DECTRACE || DECCHECK427+/* Macros for accessing decimal32 fields. These assume the argument428+ is a reference (pointer) to the decimal32 structure, and the429+ decimal32 is in network byte order (big-endian) */430+// Get sign431+#define decimal32Sign(d) ((unsigned)(d)->bytes[0]>>7)432+433+// Get combination field434+#define decimal32Comb(d) (((d)->bytes[0] & 0x7c)>>2)435+436+// Get exponent continuation [does not remove bias]437+#define decimal32ExpCon(d) ((((d)->bytes[0] & 0x03)<<4) \438+ | ((unsigned)(d)->bytes[1]>>4))439+440+// Set sign [this assumes sign previously 0]441+#define decimal32SetSign(d, b) { \442+ (d)->bytes[0]|=((unsigned)(b)<<7);}443+444+// Set exponent continuation [does not apply bias]445+// This assumes range has been checked and exponent previously 0;446+// type of exponent must be unsigned447+#define decimal32SetExpCon(d, e) { \448+ (d)->bytes[0]|=(uByte)((e)>>4); \449+ (d)->bytes[1]|=(uByte)(((e)&0x0F)<<4);}450+451+/* ------------------------------------------------------------------ */452+/* decimal32Show -- display a decimal32 in hexadecimal [debug aid] */453+/* d32 -- the number to show */454+/* ------------------------------------------------------------------ */455+// Also shows sign/cob/expconfields extracted - valid bigendian only456+void decimal32Show(const decimal32 *d32) {457+ char buf[DECIMAL32_Bytes*2+1];458+ Int i, j=0;459+460+ if (DECLITEND) {461+ for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {462+ sprintf(&buf[j], "%02x", d32->bytes[3-i]);463+ }464+ printf(" D32> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,465+ d32->bytes[3]>>7, (d32->bytes[3]>>2)&0x1f,466+ ((d32->bytes[3]&0x3)<<4)| (d32->bytes[2]>>4));467+ }468+ else {469+ for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {470+ sprintf(&buf[j], "%02x", d32->bytes[i]);471+ }472+ printf(" D32> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,473+ decimal32Sign(d32), decimal32Comb(d32), decimal32ExpCon(d32));474+ }475+ } // decimal32Show476+#endifadded:src/decNumber/decimal32.h+81 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 32-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2006. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECIMAL32)21+ #define DECIMAL3222+ #define DEC32NAME "decimal32" /* Short name */23+ #define DEC32FULLNAME "Decimal 32-bit Number" /* Verbose name */24+ #define DEC32AUTHOR "Mike Cowlishaw" /* Who to blame */25+26+ /* parameters for decimal32s */27+ #define DECIMAL32_Bytes 4 /* length */28+ #define DECIMAL32_Pmax 7 /* maximum precision (digits) */29+ #define DECIMAL32_Emax 96 /* maximum adjusted exponent */30+ #define DECIMAL32_Emin -95 /* minimum adjusted exponent */31+ #define DECIMAL32_Bias 101 /* bias for the exponent */32+ #define DECIMAL32_String 15 /* maximum string length, +1 */33+ #define DECIMAL32_EconL 6 /* exp. continuation length */34+ /* highest biased exponent (Elimit-1) */35+ #define DECIMAL32_Ehigh (DECIMAL32_Emax+DECIMAL32_Bias-DECIMAL32_Pmax+1)36+37+ /* check enough digits, if pre-defined */38+ #if defined(DECNUMDIGITS)39+ #if (DECNUMDIGITS<DECIMAL32_Pmax)40+ #error decimal32.h needs pre-defined DECNUMDIGITS>=7 for safe use41+ #endif42+ #endif43+44+ #ifndef DECNUMDIGITS45+ #define DECNUMDIGITS DECIMAL32_Pmax /* size if not already defined*/46+ #endif47+ #ifndef DECNUMBER48+ #include "decNumber.h" /* context and number library */49+ #endif50+51+ /* Decimal 32-bit type, accessible by bytes */52+ typedef struct {53+ uint8_t bytes[DECIMAL32_Bytes]; /* decimal32: 1, 5, 6, 20 bits*/54+ } decimal32;55+56+ /* special values [top byte excluding sign bit; last two bits are */57+ /* don't-care for Infinity on input, last bit don't-care for NaN] */58+ #if !defined(DECIMAL_NaN)59+ #define DECIMAL_NaN 0x7c /* 0 11111 00 NaN */60+ #define DECIMAL_sNaN 0x7e /* 0 11111 10 sNaN */61+ #define DECIMAL_Inf 0x78 /* 0 11110 00 Infinity */62+ #endif63+64+ /* ---------------------------------------------------------------- */65+ /* Routines */66+ /* ---------------------------------------------------------------- */67+ /* String conversions */68+ decimal32 * decimal32FromString(decimal32 *, const char *, decContext *);69+ char * decimal32ToString(const decimal32 *, char *);70+ char * decimal32ToEngString(const decimal32 *, char *);71+72+ /* decNumber conversions */73+ decimal32 * decimal32FromNumber(decimal32 *, const decNumber *,74+ decContext *);75+ decNumber * decimal32ToNumber(const decimal32 *, decNumber *);76+77+ /* Format-dependent utilities */78+ uint32_t decimal32IsCanonical(const decimal32 *);79+ decimal32 * decimal32Canonical(decimal32 *, const decimal32 *);80+81+#endifadded:src/decNumber/decimal64.c+839 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 64-bit format module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2009. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for decimal64 format numbers. */20+/* Conversions are supplied to and from decNumber and String. */21+/* */22+/* This is used when decNumber provides operations, either for all */23+/* operations or as a proxy between decNumber and decSingle. */24+/* */25+/* Error handling is the same as decNumber (qv.). */26+/* ------------------------------------------------------------------ */27+#include <string.h> // [for memset/memcpy]28+#include <stdio.h> // [for printf]29+30+#define DECNUMDIGITS 16 // make decNumbers with space for 1631+#include "decNumber.h" // base number library32+#include "decNumberLocal.h" // decNumber local types, etc.33+#include "decimal64.h" // our primary include34+35+/* Utility routines and tables [in decimal64.c]; externs for C++ */36+// DPD2BIN and the reverse are renamed to prevent link-time conflict37+// if decQuad is also built in the same executable38+#define DPD2BIN DPD2BINx39+#define BIN2DPD BIN2DPDx40+extern const uInt COMBEXP[32], COMBMSD[32];41+extern const uShort DPD2BIN[1024];42+extern const uShort BIN2DPD[1000];43+extern const uByte BIN2CHAR[4001];44+45+extern void decDigitsFromDPD(decNumber *, const uInt *, Int);46+extern void decDigitsToDPD(const decNumber *, uInt *, Int);47+48+#if DECTRACE || DECCHECK49+void decimal64Show(const decimal64 *); // for debug50+extern void decNumberShow(const decNumber *); // ..51+#endif52+53+/* Useful macro */54+// Clear a structure (e.g., a decNumber)55+#define DEC_clear(d) memset(d, 0, sizeof(*d))56+57+/* define and include the tables to use for conversions */58+#define DEC_BIN2CHAR 159+#define DEC_DPD2BIN 160+#define DEC_BIN2DPD 1 // used for all sizes61+#include "decDPD.h" // lookup tables62+63+/* ------------------------------------------------------------------ */64+/* decimal64FromNumber -- convert decNumber to decimal64 */65+/* */66+/* ds is the target decimal64 */67+/* dn is the source number (assumed valid) */68+/* set is the context, used only for reporting errors */69+/* */70+/* The set argument is used only for status reporting and for the */71+/* rounding mode (used if the coefficient is more than DECIMAL64_Pmax */72+/* digits or an overflow is detected). If the exponent is out of the */73+/* valid range then Overflow or Underflow will be raised. */74+/* After Underflow a subnormal result is possible. */75+/* */76+/* DEC_Clamped is set if the number has to be 'folded down' to fit, */77+/* by reducing its exponent and multiplying the coefficient by a */78+/* power of ten, or if the exponent on a zero had to be clamped. */79+/* ------------------------------------------------------------------ */80+decimal64 * decimal64FromNumber(decimal64 *d64, const decNumber *dn,81+ decContext *set) {82+ uInt status=0; // status accumulator83+ Int ae; // adjusted exponent84+ decNumber dw; // work85+ decContext dc; // ..86+ uInt comb, exp; // ..87+ uInt uiwork; // for macros88+ uInt targar[2]={0, 0}; // target 64-bit89+ #define targhi targar[1] // name the word with the sign90+ #define targlo targar[0] // and the other91+92+ // If the number has too many digits, or the exponent could be93+ // out of range then reduce the number under the appropriate94+ // constraints. This could push the number to Infinity or zero,95+ // so this check and rounding must be done before generating the96+ // decimal64]97+ ae=dn->exponent+dn->digits-1; // [0 if special]98+ if (dn->digits>DECIMAL64_Pmax // too many digits99+ || ae>DECIMAL64_Emax // likely overflow100+ || ae<DECIMAL64_Emin) { // likely underflow101+ decContextDefault(&dc, DEC_INIT_DECIMAL64); // [no traps]102+ dc.round=set->round; // use supplied rounding103+ decNumberPlus(&dw, dn, &dc); // (round and check)104+ // [this changes -0 to 0, so enforce the sign...]105+ dw.bits|=dn->bits&DECNEG;106+ status=dc.status; // save status107+ dn=&dw; // use the work number108+ } // maybe out of range109+110+ if (dn->bits&DECSPECIAL) { // a special value111+ if (dn->bits&DECINF) targhi=DECIMAL_Inf<<24;112+ else { // sNaN or qNaN113+ if ((*dn->lsu!=0 || dn->digits>1) // non-zero coefficient114+ && (dn->digits<DECIMAL64_Pmax)) { // coefficient fits115+ decDigitsToDPD(dn, targar, 0);116+ }117+ if (dn->bits&DECNAN) targhi|=DECIMAL_NaN<<24;118+ else targhi|=DECIMAL_sNaN<<24;119+ } // a NaN120+ } // special121+122+ else { // is finite123+ if (decNumberIsZero(dn)) { // is a zero124+ // set and clamp exponent125+ if (dn->exponent<-DECIMAL64_Bias) {126+ exp=0; // low clamp127+ status|=DEC_Clamped;128+ }129+ else {130+ exp=dn->exponent+DECIMAL64_Bias; // bias exponent131+ if (exp>DECIMAL64_Ehigh) { // top clamp132+ exp=DECIMAL64_Ehigh;133+ status|=DEC_Clamped;134+ }135+ }136+ comb=(exp>>5) & 0x18; // msd=0, exp top 2 bits ..137+ }138+ else { // non-zero finite number139+ uInt msd; // work140+ Int pad=0; // coefficient pad digits141+142+ // the dn is known to fit, but it may need to be padded143+ exp=(uInt)(dn->exponent+DECIMAL64_Bias); // bias exponent144+ if (exp>DECIMAL64_Ehigh) { // fold-down case145+ pad=exp-DECIMAL64_Ehigh;146+ exp=DECIMAL64_Ehigh; // [to maximum]147+ status|=DEC_Clamped;148+ }149+150+ // fastpath common case151+ if (DECDPUN==3 && pad==0) {152+ uInt dpd[6]={0,0,0,0,0,0};153+ uInt i;154+ Int d=dn->digits;155+ for (i=0; d>0; i++, d-=3) dpd[i]=BIN2DPD[dn->lsu[i]];156+ targlo =dpd[0];157+ targlo|=dpd[1]<<10;158+ targlo|=dpd[2]<<20;159+ if (dn->digits>6) {160+ targlo|=dpd[3]<<30;161+ targhi =dpd[3]>>2;162+ targhi|=dpd[4]<<8;163+ }164+ msd=dpd[5]; // [did not really need conversion]165+ }166+ else { // general case167+ decDigitsToDPD(dn, targar, pad);168+ // save and clear the top digit169+ msd=targhi>>18;170+ targhi&=0x0003ffff;171+ }172+173+ // create the combination field174+ if (msd>=8) comb=0x18 | ((exp>>7) & 0x06) | (msd & 0x01);175+ else comb=((exp>>5) & 0x18) | msd;176+ }177+ targhi|=comb<<26; // add combination field ..178+ targhi|=(exp&0xff)<<18; // .. and exponent continuation179+ } // finite180+181+ if (dn->bits&DECNEG) targhi|=0x80000000; // add sign bit182+183+ // now write to storage; this is now always endian184+ if (DECLITEND) {185+ // lo int then hi186+ UBFROMUI(d64->bytes, targar[0]);187+ UBFROMUI(d64->bytes+4, targar[1]);188+ }189+ else {190+ // hi int then lo191+ UBFROMUI(d64->bytes, targar[1]);192+ UBFROMUI(d64->bytes+4, targar[0]);193+ }194+195+ if (status!=0) decContextSetStatus(set, status); // pass on status196+ // decimal64Show(d64);197+ return d64;198+ } // decimal64FromNumber199+200+/* ------------------------------------------------------------------ */201+/* decimal64ToNumber -- convert decimal64 to decNumber */202+/* d64 is the source decimal64 */203+/* dn is the target number, with appropriate space */204+/* No error is possible. */205+/* ------------------------------------------------------------------ */206+decNumber * decimal64ToNumber(const decimal64 *d64, decNumber *dn) {207+ uInt msd; // coefficient MSD208+ uInt exp; // exponent top two bits209+ uInt comb; // combination field210+ Int need; // work211+ uInt uiwork; // for macros212+ uInt sourar[2]; // source 64-bit213+ #define sourhi sourar[1] // name the word with the sign214+ #define sourlo sourar[0] // and the lower word215+216+ // load source from storage; this is endian217+ if (DECLITEND) {218+ sourlo=UBTOUI(d64->bytes ); // directly load the low int219+ sourhi=UBTOUI(d64->bytes+4); // then the high int220+ }221+ else {222+ sourhi=UBTOUI(d64->bytes ); // directly load the high int223+ sourlo=UBTOUI(d64->bytes+4); // then the low int224+ }225+226+ comb=(sourhi>>26)&0x1f; // combination field227+228+ decNumberZero(dn); // clean number229+ if (sourhi&0x80000000) dn->bits=DECNEG; // set sign if negative230+231+ msd=COMBMSD[comb]; // decode the combination field232+ exp=COMBEXP[comb]; // ..233+234+ if (exp==3) { // is a special235+ if (msd==0) {236+ dn->bits|=DECINF;237+ return dn; // no coefficient needed238+ }239+ else if (sourhi&0x02000000) dn->bits|=DECSNAN;240+ else dn->bits|=DECNAN;241+ msd=0; // no top digit242+ }243+ else { // is a finite number244+ dn->exponent=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias; // unbiased245+ }246+247+ // get the coefficient248+ sourhi&=0x0003ffff; // clean coefficient continuation249+ if (msd) { // non-zero msd250+ sourhi|=msd<<18; // prefix to coefficient251+ need=6; // process 6 declets252+ }253+ else { // msd=0254+ if (!sourhi) { // top word 0255+ if (!sourlo) return dn; // easy: coefficient is 0256+ need=3; // process at least 3 declets257+ if (sourlo&0xc0000000) need++; // process 4 declets258+ // [could reduce some more, here]259+ }260+ else { // some bits in top word, msd=0261+ need=4; // process at least 4 declets262+ if (sourhi&0x0003ff00) need++; // top declet!=0, process 5263+ }264+ } //msd=0265+266+ decDigitsFromDPD(dn, sourar, need); // process declets267+ return dn;268+ } // decimal64ToNumber269+270+271+/* ------------------------------------------------------------------ */272+/* to-scientific-string -- conversion to numeric string */273+/* to-engineering-string -- conversion to numeric string */274+/* */275+/* decimal64ToString(d64, string); */276+/* decimal64ToEngString(d64, string); */277+/* */278+/* d64 is the decimal64 format number to convert */279+/* string is the string where the result will be laid out */280+/* */281+/* string must be at least 24 characters */282+/* */283+/* No error is possible, and no status can be set. */284+/* ------------------------------------------------------------------ */285+char * decimal64ToEngString(const decimal64 *d64, char *string){286+ decNumber dn; // work287+ decimal64ToNumber(d64, &dn);288+ decNumberToEngString(&dn, string);289+ return string;290+ } // decimal64ToEngString291+292+char * decimal64ToString(const decimal64 *d64, char *string){293+ uInt msd; // coefficient MSD294+ Int exp; // exponent top two bits or full295+ uInt comb; // combination field296+ char *cstart; // coefficient start297+ char *c; // output pointer in string298+ const uByte *u; // work299+ char *s, *t; // .. (source, target)300+ Int dpd; // ..301+ Int pre, e; // ..302+ uInt uiwork; // for macros303+304+ uInt sourar[2]; // source 64-bit305+ #define sourhi sourar[1] // name the word with the sign306+ #define sourlo sourar[0] // and the lower word307+308+ // load source from storage; this is endian309+ if (DECLITEND) {310+ sourlo=UBTOUI(d64->bytes ); // directly load the low int311+ sourhi=UBTOUI(d64->bytes+4); // then the high int312+ }313+ else {314+ sourhi=UBTOUI(d64->bytes ); // directly load the high int315+ sourlo=UBTOUI(d64->bytes+4); // then the low int316+ }317+318+ c=string; // where result will go319+ if (((Int)sourhi)<0) *c++='-'; // handle sign320+321+ comb=(sourhi>>26)&0x1f; // combination field322+ msd=COMBMSD[comb]; // decode the combination field323+ exp=COMBEXP[comb]; // ..324+325+ if (exp==3) {326+ if (msd==0) { // infinity327+ strcpy(c, "Inf");328+ strcpy(c+3, "inity");329+ return string; // easy330+ }331+ if (sourhi&0x02000000) *c++='s'; // sNaN332+ strcpy(c, "NaN"); // complete word333+ c+=3; // step past334+ if (sourlo==0 && (sourhi&0x0003ffff)==0) return string; // zero payload335+ // otherwise drop through to add integer; set correct exp336+ exp=0; msd=0; // setup for following code337+ }338+ else exp=(exp<<8)+((sourhi>>18)&0xff)-DECIMAL64_Bias;339+340+ // convert 16 digits of significand to characters341+ cstart=c; // save start of coefficient342+ if (msd) *c++='0'+(char)msd; // non-zero most significant digit343+344+ // Now decode the declets. After extracting each one, it is345+ // decoded to binary and then to a 4-char sequence by table lookup;346+ // the 4-chars are a 1-char length (significant digits, except 000347+ // has length 0). This allows us to left-align the first declet348+ // with non-zero content, then remaining ones are full 3-char349+ // length. We use fixed-length memcpys because variable-length350+ // causes a subroutine call in GCC. (These are length 4 for speed351+ // and are safe because the array has an extra terminator byte.)352+ #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; \353+ if (c!=cstart) {memcpy(c, u+1, 4); c+=3;} \354+ else if (*u) {memcpy(c, u+4-*u, 4); c+=*u;}355+356+ dpd=(sourhi>>8)&0x3ff; // declet 1357+ dpd2char;358+ dpd=((sourhi&0xff)<<2) | (sourlo>>30); // declet 2359+ dpd2char;360+ dpd=(sourlo>>20)&0x3ff; // declet 3361+ dpd2char;362+ dpd=(sourlo>>10)&0x3ff; // declet 4363+ dpd2char;364+ dpd=(sourlo)&0x3ff; // declet 5365+ dpd2char;366+367+ if (c==cstart) *c++='0'; // all zeros -- make 0368+369+ if (exp==0) { // integer or NaN case -- easy370+ *c='\0'; // terminate371+ return string;372+ }373+374+ /* non-0 exponent */375+ e=0; // assume no E376+ pre=c-cstart+exp;377+ // [here, pre-exp is the digits count (==1 for zero)]378+ if (exp>0 || pre<-5) { // need exponential form379+ e=pre-1; // calculate E value380+ pre=1; // assume one digit before '.'381+ } // exponential form382+383+ /* modify the coefficient, adding 0s, '.', and E+nn as needed */384+ s=c-1; // source (LSD)385+ if (pre>0) { // ddd.ddd (plain), perhaps with E386+ char *dotat=cstart+pre;387+ if (dotat<c) { // if embedded dot needed...388+ t=c; // target389+ for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap390+ *t='.'; // insert the dot391+ c++; // length increased by one392+ }393+394+ // finally add the E-part, if needed; it will never be 0, and has395+ // a maximum length of 3 digits396+ if (e!=0) {397+ *c++='E'; // starts with E398+ *c++='+'; // assume positive399+ if (e<0) {400+ *(c-1)='-'; // oops, need '-'401+ e=-e; // uInt, please402+ }403+ u=&BIN2CHAR[e*4]; // -> length byte404+ memcpy(c, u+4-*u, 4); // copy fixed 4 characters [is safe]405+ c+=*u; // bump pointer appropriately406+ }407+ *c='\0'; // add terminator408+ //printf("res %s\n", string);409+ return string;410+ } // pre>0411+412+ /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */413+ t=c+1-pre;414+ *(t+1)='\0'; // can add terminator now415+ for (; s>=cstart; s--, t--) *t=*s; // shift whole coefficient right416+ c=cstart;417+ *c++='0'; // always starts with 0.418+ *c++='.';419+ for (; pre<0; pre++) *c++='0'; // add any 0's after '.'420+ //printf("res %s\n", string);421+ return string;422+ } // decimal64ToString423+424+/* ------------------------------------------------------------------ */425+/* to-number -- conversion from numeric string */426+/* */427+/* decimal64FromString(result, string, set); */428+/* */429+/* result is the decimal64 format number which gets the result of */430+/* the conversion */431+/* *string is the character string which should contain a valid */432+/* number (which may be a special value) */433+/* set is the context */434+/* */435+/* The context is supplied to this routine is used for error handling */436+/* (setting of status and traps) and for the rounding mode, only. */437+/* If an error occurs, the result will be a valid decimal64 NaN. */438+/* ------------------------------------------------------------------ */439+decimal64 * decimal64FromString(decimal64 *result, const char *string,440+ decContext *set) {441+ decContext dc; // work442+ decNumber dn; // ..443+444+ decContextDefault(&dc, DEC_INIT_DECIMAL64); // no traps, please445+ dc.round=set->round; // use supplied rounding446+447+ decNumberFromString(&dn, string, &dc); // will round if needed448+449+ decimal64FromNumber(result, &dn, &dc);450+ if (dc.status!=0) { // something happened451+ decContextSetStatus(set, dc.status); // .. pass it on452+ }453+ return result;454+ } // decimal64FromString455+456+/* ------------------------------------------------------------------ */457+/* decimal64IsCanonical -- test whether encoding is canonical */458+/* d64 is the source decimal64 */459+/* returns 1 if the encoding of d64 is canonical, 0 otherwise */460+/* No error is possible. */461+/* ------------------------------------------------------------------ */462+uInt decimal64IsCanonical(const decimal64 *d64) {463+ decNumber dn; // work464+ decimal64 canon; // ..465+ decContext dc; // ..466+ decContextDefault(&dc, DEC_INIT_DECIMAL64);467+ decimal64ToNumber(d64, &dn);468+ decimal64FromNumber(&canon, &dn, &dc);// canon will now be canonical469+ return memcmp(d64, &canon, DECIMAL64_Bytes)==0;470+ } // decimal64IsCanonical471+472+/* ------------------------------------------------------------------ */473+/* decimal64Canonical -- copy an encoding, ensuring it is canonical */474+/* d64 is the source decimal64 */475+/* result is the target (may be the same decimal64) */476+/* returns result */477+/* No error is possible. */478+/* ------------------------------------------------------------------ */479+decimal64 * decimal64Canonical(decimal64 *result, const decimal64 *d64) {480+ decNumber dn; // work481+ decContext dc; // ..482+ decContextDefault(&dc, DEC_INIT_DECIMAL64);483+ decimal64ToNumber(d64, &dn);484+ decimal64FromNumber(result, &dn, &dc);// result will now be canonical485+ return result;486+ } // decimal64Canonical487+488+#if DECTRACE || DECCHECK489+/* Macros for accessing decimal64 fields. These assume the490+ argument is a reference (pointer) to the decimal64 structure,491+ and the decimal64 is in network byte order (big-endian) */492+// Get sign493+#define decimal64Sign(d) ((unsigned)(d)->bytes[0]>>7)494+495+// Get combination field496+#define decimal64Comb(d) (((d)->bytes[0] & 0x7c)>>2)497+498+// Get exponent continuation [does not remove bias]499+#define decimal64ExpCon(d) ((((d)->bytes[0] & 0x03)<<6) \500+ | ((unsigned)(d)->bytes[1]>>2))501+502+// Set sign [this assumes sign previously 0]503+#define decimal64SetSign(d, b) { \504+ (d)->bytes[0]|=((unsigned)(b)<<7);}505+506+// Set exponent continuation [does not apply bias]507+// This assumes range has been checked and exponent previously 0;508+// type of exponent must be unsigned509+#define decimal64SetExpCon(d, e) { \510+ (d)->bytes[0]|=(uByte)((e)>>6); \511+ (d)->bytes[1]|=(uByte)(((e)&0x3F)<<2);}512+513+/* ------------------------------------------------------------------ */514+/* decimal64Show -- display a decimal64 in hexadecimal [debug aid] */515+/* d64 -- the number to show */516+/* ------------------------------------------------------------------ */517+// Also shows sign/cob/expconfields extracted518+void decimal64Show(const decimal64 *d64) {519+ char buf[DECIMAL64_Bytes*2+1];520+ Int i, j=0;521+522+ if (DECLITEND) {523+ for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {524+ sprintf(&buf[j], "%02x", d64->bytes[7-i]);525+ }526+ printf(" D64> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,527+ d64->bytes[7]>>7, (d64->bytes[7]>>2)&0x1f,528+ ((d64->bytes[7]&0x3)<<6)| (d64->bytes[6]>>2));529+ }530+ else { // big-endian531+ for (i=0; i<DECIMAL64_Bytes; i++, j+=2) {532+ sprintf(&buf[j], "%02x", d64->bytes[i]);533+ }534+ printf(" D64> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,535+ decimal64Sign(d64), decimal64Comb(d64), decimal64ExpCon(d64));536+ }537+ } // decimal64Show538+#endif539+540+/* ================================================================== */541+/* Shared utility routines and tables */542+/* ================================================================== */543+// define and include the conversion tables to use for shared code544+#if DECDPUN==3545+ #define DEC_DPD2BIN 1546+#else547+ #define DEC_DPD2BCD 1548+#endif549+#include "decDPD.h" // lookup tables550+551+// The maximum number of decNumberUnits needed for a working copy of552+// the units array is the ceiling of digits/DECDPUN, where digits is553+// the maximum number of digits in any of the formats for which this554+// is used. decimal128.h must not be included in this module, so, as555+// a very special case, that number is defined as a literal here.556+#define DECMAX754 34557+#define DECMAXUNITS ((DECMAX754+DECDPUN-1)/DECDPUN)558+559+/* ------------------------------------------------------------------ */560+/* Combination field lookup tables (uInts to save measurable work) */561+/* */562+/* COMBEXP - 2-bit most-significant-bits of exponent */563+/* [11 if an Infinity or NaN] */564+/* COMBMSD - 4-bit most-significant-digit */565+/* [0=Infinity, 1=NaN if COMBEXP=11] */566+/* */567+/* Both are indexed by the 5-bit combination field (0-31) */568+/* ------------------------------------------------------------------ */569+const uInt COMBEXP[32]={0, 0, 0, 0, 0, 0, 0, 0,570+ 1, 1, 1, 1, 1, 1, 1, 1,571+ 2, 2, 2, 2, 2, 2, 2, 2,572+ 0, 0, 1, 1, 2, 2, 3, 3};573+const uInt COMBMSD[32]={0, 1, 2, 3, 4, 5, 6, 7,574+ 0, 1, 2, 3, 4, 5, 6, 7,575+ 0, 1, 2, 3, 4, 5, 6, 7,576+ 8, 9, 8, 9, 8, 9, 0, 1};577+578+/* ------------------------------------------------------------------ */579+/* decDigitsToDPD -- pack coefficient into DPD form */580+/* */581+/* dn is the source number (assumed valid, max DECMAX754 digits) */582+/* targ is 1, 2, or 4-element uInt array, which the caller must */583+/* have cleared to zeros */584+/* shift is the number of 0 digits to add on the right (normally 0) */585+/* */586+/* The coefficient must be known small enough to fit. The full */587+/* coefficient is copied, including the leading 'odd' digit. This */588+/* digit is retrieved and packed into the combination field by the */589+/* caller. */590+/* */591+/* The target uInts are altered only as necessary to receive the */592+/* digits of the decNumber. When more than one uInt is needed, they */593+/* are filled from left to right (that is, the uInt at offset 0 will */594+/* end up with the least-significant digits). */595+/* */596+/* shift is used for 'fold-down' padding. */597+/* */598+/* No error is possible. */599+/* ------------------------------------------------------------------ */600+#if DECDPUN<=4601+// Constant multipliers for divide-by-power-of five using reciprocal602+// multiply, after removing powers of 2 by shifting, and final shift603+// of 17 [we only need up to **4]604+static const uInt multies[]={131073, 26215, 5243, 1049, 210};605+// QUOT10 -- macro to return the quotient of unit u divided by 10**n606+#define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)607+#endif608+void decDigitsToDPD(const decNumber *dn, uInt *targ, Int shift) {609+ Int cut; // work610+ Int n; // output bunch counter611+ Int digits=dn->digits; // digit countdown612+ uInt dpd; // densely packed decimal value613+ uInt bin; // binary value 0-999614+ uInt *uout=targ; // -> current output uInt615+ uInt uoff=0; // -> current output offset [from right]616+ const Unit *inu=dn->lsu; // -> current input unit617+ Unit uar[DECMAXUNITS]; // working copy of units, iff shifted618+ #if DECDPUN!=3 // not fast path619+ Unit in; // current unit620+ #endif621+622+ if (shift!=0) { // shift towards most significant required623+ // shift the units array to the left by pad digits and copy624+ // [this code is a special case of decShiftToMost, which could625+ // be used instead if exposed and the array were copied first]626+ const Unit *source; // ..627+ Unit *target, *first; // ..628+ uInt next=0; // work629+630+ source=dn->lsu+D2U(digits)-1; // where msu comes from631+ target=uar+D2U(digits)-1+D2U(shift);// where upper part of first cut goes632+ cut=DECDPUN-MSUDIGITS(shift); // where to slice633+ if (cut==0) { // unit-boundary case634+ for (; source>=dn->lsu; source--, target--) *target=*source;635+ }636+ else {637+ first=uar+D2U(digits+shift)-1; // where msu will end up638+ for (; source>=dn->lsu; source--, target--) {639+ // split the source Unit and accumulate remainder for next640+ #if DECDPUN<=4641+ uInt quot=QUOT10(*source, cut);642+ uInt rem=*source-quot*DECPOWERS[cut];643+ next+=quot;644+ #else645+ uInt rem=*source%DECPOWERS[cut];646+ next+=*source/DECPOWERS[cut];647+ #endif648+ if (target<=first) *target=(Unit)next; // write to target iff valid649+ next=rem*DECPOWERS[DECDPUN-cut]; // save remainder for next Unit650+ }651+ } // shift-move652+ // propagate remainder to one below and clear the rest653+ for (; target>=uar; target--) {654+ *target=(Unit)next;655+ next=0;656+ }657+ digits+=shift; // add count (shift) of zeros added658+ inu=uar; // use units in working array659+ }660+661+ /* now densely pack the coefficient into DPD declets */662+663+ #if DECDPUN!=3 // not fast path664+ in=*inu; // current unit665+ cut=0; // at lowest digit666+ bin=0; // [keep compiler quiet]667+ #endif668+669+ for(n=0; digits>0; n++) { // each output bunch670+ #if DECDPUN==3 // fast path, 3-at-a-time671+ bin=*inu; // 3 digits ready for convert672+ digits-=3; // [may go negative]673+ inu++; // may need another674+675+ #else // must collect digit-by-digit676+ Unit dig; // current digit677+ Int j; // digit-in-declet count678+ for (j=0; j<3; j++) {679+ #if DECDPUN<=4680+ Unit temp=(Unit)((uInt)(in*6554)>>16);681+ dig=(Unit)(in-X10(temp));682+ in=temp;683+ #else684+ dig=in%10;685+ in=in/10;686+ #endif687+ if (j==0) bin=dig;688+ else if (j==1) bin+=X10(dig);689+ else /* j==2 */ bin+=X100(dig);690+ digits--;691+ if (digits==0) break; // [also protects *inu below]692+ cut++;693+ if (cut==DECDPUN) {inu++; in=*inu; cut=0;}694+ }695+ #endif696+ // here there are 3 digits in bin, or have used all input digits697+698+ dpd=BIN2DPD[bin];699+700+ // write declet to uInt array701+ *uout|=dpd<<uoff;702+ uoff+=10;703+ if (uoff<32) continue; // no uInt boundary cross704+ uout++;705+ uoff-=32;706+ *uout|=dpd>>(10-uoff); // collect top bits707+ } // n declets708+ return;709+ } // decDigitsToDPD710+711+/* ------------------------------------------------------------------ */712+/* decDigitsFromDPD -- unpack a format's coefficient */713+/* */714+/* dn is the target number, with 7, 16, or 34-digit space. */715+/* sour is a 1, 2, or 4-element uInt array containing only declets */716+/* declets is the number of (right-aligned) declets in sour to */717+/* be processed. This may be 1 more than the obvious number in */718+/* a format, as any top digit is prefixed to the coefficient */719+/* continuation field. It also may be as small as 1, as the */720+/* caller may pre-process leading zero declets. */721+/* */722+/* When doing the 'extra declet' case care is taken to avoid writing */723+/* extra digits when there are leading zeros, as these could overflow */724+/* the units array when DECDPUN is not 3. */725+/* */726+/* The target uInts are used only as necessary to process declets */727+/* declets into the decNumber. When more than one uInt is needed, */728+/* they are used from left to right (that is, the uInt at offset 0 */729+/* provides the least-significant digits). */730+/* */731+/* dn->digits is set, but not the sign or exponent. */732+/* No error is possible [the redundant 888 codes are allowed]. */733+/* ------------------------------------------------------------------ */734+void decDigitsFromDPD(decNumber *dn, const uInt *sour, Int declets) {735+736+ uInt dpd; // collector for 10 bits737+ Int n; // counter738+ Unit *uout=dn->lsu; // -> current output unit739+ Unit *last=uout; // will be unit containing msd740+ const uInt *uin=sour; // -> current input uInt741+ uInt uoff=0; // -> current input offset [from right]742+743+ #if DECDPUN!=3744+ uInt bcd; // BCD result745+ uInt nibble; // work746+ Unit out=0; // accumulator747+ Int cut=0; // power of ten in current unit748+ #endif749+ #if DECDPUN>4750+ uInt const *pow; // work751+ #endif752+753+ // Expand the densely-packed integer, right to left754+ for (n=declets-1; n>=0; n--) { // count down declets of 10 bits755+ dpd=*uin>>uoff;756+ uoff+=10;757+ if (uoff>32) { // crossed uInt boundary758+ uin++;759+ uoff-=32; // [if using this code for wider, check this]760+ dpd|=*uin<<(10-uoff); // get waiting bits761+ }762+ dpd&=0x3ff; // clear uninteresting bits763+764+ #if DECDPUN==3765+ if (dpd==0) *uout=0;766+ else {767+ *uout=DPD2BIN[dpd]; // convert 10 bits to binary 0-999768+ last=uout; // record most significant unit769+ }770+ uout++;771+ } // n772+773+ #else // DECDPUN!=3774+ if (dpd==0) { // fastpath [e.g., leading zeros]775+ // write out three 0 digits (nibbles); out may have digit(s)776+ cut++;777+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}778+ if (n==0) break; // [as below, works even if MSD=0]779+ cut++;780+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}781+ cut++;782+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}783+ continue;784+ }785+786+ bcd=DPD2BCD[dpd]; // convert 10 bits to 12 bits BCD787+788+ // now accumulate the 3 BCD nibbles into units789+ nibble=bcd & 0x00f;790+ if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);791+ cut++;792+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}793+ bcd>>=4;794+795+ // if this is the last declet and the remaining nibbles in bcd796+ // are 00 then process no more nibbles, because this could be797+ // the 'odd' MSD declet and writing any more Units would then798+ // overflow the unit array799+ if (n==0 && !bcd) break;800+801+ nibble=bcd & 0x00f;802+ if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);803+ cut++;804+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}805+ bcd>>=4;806+807+ nibble=bcd & 0x00f;808+ if (nibble) out=(Unit)(out+nibble*DECPOWERS[cut]);809+ cut++;810+ if (cut==DECDPUN) {*uout=out; if (out) {last=uout; out=0;} uout++; cut=0;}811+ } // n812+ if (cut!=0) { // some more left over813+ *uout=out; // write out final unit814+ if (out) last=uout; // and note if non-zero815+ }816+ #endif817+818+ // here, last points to the most significant unit with digits;819+ // inspect it to get the final digits count -- this is essentially820+ // the same code as decGetDigits in decNumber.c821+ dn->digits=(last-dn->lsu)*DECDPUN+1; // floor of digits, plus822+ // must be at least 1 digit823+ #if DECDPUN>1824+ if (*last<10) return; // common odd digit or 0825+ dn->digits++; // must be 2 at least826+ #if DECDPUN>2827+ if (*last<100) return; // 10-99828+ dn->digits++; // must be 3 at least829+ #if DECDPUN>3830+ if (*last<1000) return; // 100-999831+ dn->digits++; // must be 4 at least832+ #if DECDPUN>4833+ for (pow=&DECPOWERS[4]; *last>=*pow; pow++) dn->digits++;834+ #endif835+ #endif836+ #endif837+ #endif838+ return;839+ } //decDigitsFromDPDadded:src/decNumber/decimal64.h+83 added
1+/* ------------------------------------------------------------------ */2+/* Decimal 64-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2005. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECIMAL64)21+ #define DECIMAL6422+ #define DEC64NAME "decimal64" /* Short name */23+ #define DEC64FULLNAME "Decimal 64-bit Number" /* Verbose name */24+ #define DEC64AUTHOR "Mike Cowlishaw" /* Who to blame */25+26+27+ /* parameters for decimal64s */28+ #define DECIMAL64_Bytes 8 /* length */29+ #define DECIMAL64_Pmax 16 /* maximum precision (digits) */30+ #define DECIMAL64_Emax 384 /* maximum adjusted exponent */31+ #define DECIMAL64_Emin -383 /* minimum adjusted exponent */32+ #define DECIMAL64_Bias 398 /* bias for the exponent */33+ #define DECIMAL64_String 24 /* maximum string length, +1 */34+ #define DECIMAL64_EconL 8 /* exp. continuation length */35+ /* highest biased exponent (Elimit-1) */36+ #define DECIMAL64_Ehigh (DECIMAL64_Emax+DECIMAL64_Bias-DECIMAL64_Pmax+1)37+38+ /* check enough digits, if pre-defined */39+ #if defined(DECNUMDIGITS)40+ #if (DECNUMDIGITS<DECIMAL64_Pmax)41+ #error decimal64.h needs pre-defined DECNUMDIGITS>=16 for safe use42+ #endif43+ #endif44+45+46+ #ifndef DECNUMDIGITS47+ #define DECNUMDIGITS DECIMAL64_Pmax /* size if not already defined*/48+ #endif49+ #ifndef DECNUMBER50+ #include "decNumber.h" /* context and number library */51+ #endif52+53+ /* Decimal 64-bit type, accessible by bytes */54+ typedef struct {55+ uint8_t bytes[DECIMAL64_Bytes]; /* decimal64: 1, 5, 8, 50 bits*/56+ } decimal64;57+58+ /* special values [top byte excluding sign bit; last two bits are */59+ /* don't-care for Infinity on input, last bit don't-care for NaN] */60+ #if !defined(DECIMAL_NaN)61+ #define DECIMAL_NaN 0x7c /* 0 11111 00 NaN */62+ #define DECIMAL_sNaN 0x7e /* 0 11111 10 sNaN */63+ #define DECIMAL_Inf 0x78 /* 0 11110 00 Infinity */64+ #endif65+66+ /* ---------------------------------------------------------------- */67+ /* Routines */68+ /* ---------------------------------------------------------------- */69+ /* String conversions */70+ decimal64 * decimal64FromString(decimal64 *, const char *, decContext *);71+ char * decimal64ToString(const decimal64 *, char *);72+ char * decimal64ToEngString(const decimal64 *, char *);73+74+ /* decNumber conversions */75+ decimal64 * decimal64FromNumber(decimal64 *, const decNumber *,76+ decContext *);77+ decNumber * decimal64ToNumber(const decimal64 *, decNumber *);78+79+ /* Format-dependent utilities */80+ uint32_t decimal64IsCanonical(const decimal64 *);81+ decimal64 * decimal64Canonical(decimal64 *, const decimal64 *);82+83+#endifadded:src/decNumber/decNumber.c+8141 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number arithmetic module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2009. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for arbitrary-precision General */20+/* Decimal Arithmetic as defined in the specification which may be */21+/* found on the General Decimal Arithmetic pages. It implements both */22+/* the full ('extended') arithmetic and the simpler ('subset') */23+/* arithmetic. */24+/* */25+/* Usage notes: */26+/* */27+/* 1. This code is ANSI C89 except: */28+/* */29+/* a) C99 line comments (double forward slash) are used. (Most C */30+/* compilers accept these. If yours does not, a simple script */31+/* can be used to convert them to ANSI C comments.) */32+/* */33+/* b) Types from C99 stdint.h are used. If you do not have this */34+/* header file, see the User's Guide section of the decNumber */35+/* documentation; this lists the necessary definitions. */36+/* */37+/* c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and */38+/* uint64_t types may be used. To avoid these, set DECUSE64=0 */39+/* and DECDPUN<=4 (see documentation). */40+/* */41+/* The code also conforms to C99 restrictions; in particular, */42+/* strict aliasing rules are observed. */43+/* */44+/* 2. The decNumber format which this library uses is optimized for */45+/* efficient processing of relatively short numbers; in particular */46+/* it allows the use of fixed sized structures and minimizes copy */47+/* and move operations. It does, however, support arbitrary */48+/* precision (up to 999,999,999 digits) and arbitrary exponent */49+/* range (Emax in the range 0 through 999,999,999 and Emin in the */50+/* range -999,999,999 through 0). Mathematical functions (for */51+/* example decNumberExp) as identified below are restricted more */52+/* tightly: digits, emax, and -emin in the context must be <= */53+/* DEC_MAX_MATH (999999), and their operand(s) must be within */54+/* these bounds. */55+/* */56+/* 3. Logical functions are further restricted; their operands must */57+/* be finite, positive, have an exponent of zero, and all digits */58+/* must be either 0 or 1. The result will only contain digits */59+/* which are 0 or 1 (and will have exponent=0 and a sign of 0). */60+/* */61+/* 4. Operands to operator functions are never modified unless they */62+/* are also specified to be the result number (which is always */63+/* permitted). Other than that case, operands must not overlap. */64+/* */65+/* 5. Error handling: the type of the error is ORed into the status */66+/* flags in the current context (decContext structure). The */67+/* SIGFPE signal is then raised if the corresponding trap-enabler */68+/* flag in the decContext is set (is 1). */69+/* */70+/* It is the responsibility of the caller to clear the status */71+/* flags as required. */72+/* */73+/* The result of any routine which returns a number will always */74+/* be a valid number (which may be a special value, such as an */75+/* Infinity or NaN). */76+/* */77+/* 6. The decNumber format is not an exchangeable concrete */78+/* representation as it comprises fields which may be machine- */79+/* dependent (packed or unpacked, or special length, for example). */80+/* Canonical conversions to and from strings are provided; other */81+/* conversions are available in separate modules. */82+/* */83+/* 7. Normally, input operands are assumed to be valid. Set DECCHECK */84+/* to 1 for extended operand checking (including NULL operands). */85+/* Results are undefined if a badly-formed structure (or a NULL */86+/* pointer to a structure) is provided, though with DECCHECK */87+/* enabled the operator routines are protected against exceptions. */88+/* (Except if the result pointer is NULL, which is unrecoverable.) */89+/* */90+/* However, the routines will never cause exceptions if they are */91+/* given well-formed operands, even if the value of the operands */92+/* is inappropriate for the operation and DECCHECK is not set. */93+/* (Except for SIGFPE, as and where documented.) */94+/* */95+/* 8. Subset arithmetic is available only if DECSUBSET is set to 1. */96+/* ------------------------------------------------------------------ */97+/* Implementation notes for maintenance of this module: */98+/* */99+/* 1. Storage leak protection: Routines which use malloc are not */100+/* permitted to use return for fastpath or error exits (i.e., */101+/* they follow strict structured programming conventions). */102+/* Instead they have a do{}while(0); construct surrounding the */103+/* code which is protected -- break may be used to exit this. */104+/* Other routines can safely use the return statement inline. */105+/* */106+/* Storage leak accounting can be enabled using DECALLOC. */107+/* */108+/* 2. All loops use the for(;;) construct. Any do construct does */109+/* not loop; it is for allocation protection as just described. */110+/* */111+/* 3. Setting status in the context must always be the very last */112+/* action in a routine, as non-0 status may raise a trap and hence */113+/* the call to set status may not return (if the handler uses long */114+/* jump). Therefore all cleanup must be done first. In general, */115+/* to achieve this status is accumulated and is only applied just */116+/* before return by calling decContextSetStatus (via decStatus). */117+/* */118+/* Routines which allocate storage cannot, in general, use the */119+/* 'top level' routines which could cause a non-returning */120+/* transfer of control. The decXxxxOp routines are safe (do not */121+/* call decStatus even if traps are set in the context) and should */122+/* be used instead (they are also a little faster). */123+/* */124+/* 4. Exponent checking is minimized by allowing the exponent to */125+/* grow outside its limits during calculations, provided that */126+/* the decFinalize function is called later. Multiplication and */127+/* division, and intermediate calculations in exponentiation, */128+/* require more careful checks because of the risk of 31-bit */129+/* overflow (the most negative valid exponent is -1999999997, for */130+/* a 999999999-digit number with adjusted exponent of -999999999). */131+/* */132+/* 5. Rounding is deferred until finalization of results, with any */133+/* 'off to the right' data being represented as a single digit */134+/* residue (in the range -1 through 9). This avoids any double- */135+/* rounding when more than one shortening takes place (for */136+/* example, when a result is subnormal). */137+/* */138+/* 6. The digits count is allowed to rise to a multiple of DECDPUN */139+/* during many operations, so whole Units are handled and exact */140+/* accounting of digits is not needed. The correct digits value */141+/* is found by decGetDigits, which accounts for leading zeros. */142+/* This must be called before any rounding if the number of digits */143+/* is not known exactly. */144+/* */145+/* 7. The multiply-by-reciprocal 'trick' is used for partitioning */146+/* numbers up to four digits, using appropriate constants. This */147+/* is not useful for longer numbers because overflow of 32 bits */148+/* would lead to 4 multiplies, which is almost as expensive as */149+/* a divide (unless a floating-point or 64-bit multiply is */150+/* assumed to be available). */151+/* */152+/* 8. Unusual abbreviations that may be used in the commentary: */153+/* lhs -- left hand side (operand, of an operation) */154+/* lsd -- least significant digit (of coefficient) */155+/* lsu -- least significant Unit (of coefficient) */156+/* msd -- most significant digit (of coefficient) */157+/* msi -- most significant item (in an array) */158+/* msu -- most significant Unit (of coefficient) */159+/* rhs -- right hand side (operand, of an operation) */160+/* +ve -- positive */161+/* -ve -- negative */162+/* ** -- raise to the power */163+/* ------------------------------------------------------------------ */164+165+#include <stdlib.h> // for malloc, free, etc.166+#include <stdio.h> // for printf [if needed]167+#include <string.h> // for strcpy168+#include <ctype.h> // for lower169+#include "decNumber.h" // base number library170+#include "decNumberLocal.h" // decNumber local types, etc.171+172+/* Constants */173+// Public lookup table used by the D2U macro174+const uByte d2utable[DECMAXD2U+1]=D2UTABLE;175+176+#define DECVERB 1 // set to 1 for verbose DECCHECK177+#define powers DECPOWERS // old internal name178+179+// Local constants180+#define DIVIDE 0x80 // Divide operators181+#define REMAINDER 0x40 // ..182+#define DIVIDEINT 0x20 // ..183+#define REMNEAR 0x10 // ..184+#define COMPARE 0x01 // Compare operators185+#define COMPMAX 0x02 // ..186+#define COMPMIN 0x03 // ..187+#define COMPTOTAL 0x04 // ..188+#define COMPNAN 0x05 // .. [NaN processing]189+#define COMPSIG 0x06 // .. [signaling COMPARE]190+#define COMPMAXMAG 0x07 // ..191+#define COMPMINMAG 0x08 // ..192+193+#define DEC_sNaN 0x40000000 // local status: sNaN signal194+#define BADINT (Int)0x80000000 // most-negative Int; error indicator195+// Next two indicate an integer >= 10**6, and its parity (bottom bit)196+#define BIGEVEN (Int)0x80000002197+#define BIGODD (Int)0x80000003198+199+static Unit uarrone[1]={1}; // Unit array of 1, used for incrementing200+201+/* Granularity-dependent code */202+#if DECDPUN<=4203+ #define eInt Int // extended integer204+ #define ueInt uInt // unsigned extended integer205+ // Constant multipliers for divide-by-power-of five using reciprocal206+ // multiply, after removing powers of 2 by shifting, and final shift207+ // of 17 [we only need up to **4]208+ static const uInt multies[]={131073, 26215, 5243, 1049, 210};209+ // QUOT10 -- macro to return the quotient of unit u divided by 10**n210+ #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)211+#else212+ // For DECDPUN>4 non-ANSI-89 64-bit types are needed.213+ #if !DECUSE64214+ #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4215+ #endif216+ #define eInt Long // extended integer217+ #define ueInt uLong // unsigned extended integer218+#endif219+220+/* Local routines */221+static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,222+ decContext *, uByte, uInt *);223+static Flag decBiStr(const char *, const char *, const char *);224+static uInt decCheckMath(const decNumber *, decContext *, uInt *);225+static void decApplyRound(decNumber *, decContext *, Int, uInt *);226+static Int decCompare(const decNumber *lhs, const decNumber *rhs, Flag);227+static decNumber * decCompareOp(decNumber *, const decNumber *,228+ const decNumber *, decContext *,229+ Flag, uInt *);230+static void decCopyFit(decNumber *, const decNumber *, decContext *,231+ Int *, uInt *);232+static decNumber * decDecap(decNumber *, Int);233+static decNumber * decDivideOp(decNumber *, const decNumber *,234+ const decNumber *, decContext *, Flag, uInt *);235+static decNumber * decExpOp(decNumber *, const decNumber *,236+ decContext *, uInt *);237+static void decFinalize(decNumber *, decContext *, Int *, uInt *);238+static Int decGetDigits(Unit *, Int);239+static Int decGetInt(const decNumber *);240+static decNumber * decLnOp(decNumber *, const decNumber *,241+ decContext *, uInt *);242+static decNumber * decMultiplyOp(decNumber *, const decNumber *,243+ const decNumber *, decContext *,244+ uInt *);245+static decNumber * decNaNs(decNumber *, const decNumber *,246+ const decNumber *, decContext *, uInt *);247+static decNumber * decQuantizeOp(decNumber *, const decNumber *,248+ const decNumber *, decContext *, Flag,249+ uInt *);250+static void decReverse(Unit *, Unit *);251+static void decSetCoeff(decNumber *, decContext *, const Unit *,252+ Int, Int *, uInt *);253+static void decSetMaxValue(decNumber *, decContext *);254+static void decSetOverflow(decNumber *, decContext *, uInt *);255+static void decSetSubnormal(decNumber *, decContext *, Int *, uInt *);256+static Int decShiftToLeast(Unit *, Int, Int);257+static Int decShiftToMost(Unit *, Int, Int);258+static void decStatus(decNumber *, uInt, decContext *);259+static void decToString(const decNumber *, char[], Flag);260+static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);261+static Int decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,262+ Unit *, Int);263+static Int decUnitCompare(const Unit *, Int, const Unit *, Int, Int);264+265+#if !DECSUBSET266+/* decFinish == decFinalize when no subset arithmetic needed */267+#define decFinish(a,b,c,d) decFinalize(a,b,c,d)268+#else269+static void decFinish(decNumber *, decContext *, Int *, uInt *);270+static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);271+#endif272+273+/* Local macros */274+// masked special-values bits275+#define SPECIALARG (rhs->bits & DECSPECIAL)276+#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)277+278+/* Diagnostic macros, etc. */279+#if DECALLOC280+// Handle malloc/free accounting. If enabled, our accountable routines281+// are used; otherwise the code just goes straight to the system malloc282+// and free routines.283+#define malloc(a) decMalloc(a)284+#define free(a) decFree(a)285+#define DECFENCE 0x5a // corruption detector286+// 'Our' malloc and free:287+static void *decMalloc(size_t);288+static void decFree(void *);289+uInt decAllocBytes=0; // count of bytes allocated290+// Note that DECALLOC code only checks for storage buffer overflow.291+// To check for memory leaks, the decAllocBytes variable must be292+// checked to be 0 at appropriate times (e.g., after the test293+// harness completes a set of tests). This checking may be unreliable294+// if the testing is done in a multi-thread environment.295+#endif296+297+#if DECCHECK298+// Optional checking routines. Enabling these means that decNumber299+// and decContext operands to operator routines are checked for300+// correctness. This roughly doubles the execution time of the301+// fastest routines (and adds 600+ bytes), so should not normally be302+// used in 'production'.303+// decCheckInexact is used to check that inexact results have a full304+// complement of digits (where appropriate -- this is not the case305+// for Quantize, for example)306+#define DECUNRESU ((decNumber *)(void *)0xffffffff)307+#define DECUNUSED ((const decNumber *)(void *)0xffffffff)308+#define DECUNCONT ((decContext *)(void *)(0xffffffff))309+static Flag decCheckOperands(decNumber *, const decNumber *,310+ const decNumber *, decContext *);311+static Flag decCheckNumber(const decNumber *);312+static void decCheckInexact(const decNumber *, decContext *);313+#endif314+315+#if DECTRACE || DECCHECK316+// Optional trace/debugging routines (may or may not be used)317+void decNumberShow(const decNumber *); // displays the components of a number318+static void decDumpAr(char, const Unit *, Int);319+#endif320+321+/* ================================================================== */322+/* Conversions */323+/* ================================================================== */324+325+/* ------------------------------------------------------------------ */326+/* from-int32 -- conversion from Int or uInt */327+/* */328+/* dn is the decNumber to receive the integer */329+/* in or uin is the integer to be converted */330+/* returns dn */331+/* */332+/* No error is possible. */333+/* ------------------------------------------------------------------ */334+decNumber * decNumberFromInt32(decNumber *dn, Int in) {335+ uInt unsig;336+ if (in>=0) unsig=in;337+ else { // negative (possibly BADINT)338+ if (in==BADINT) unsig=(uInt)1073741824*2; // special case339+ else unsig=-in; // invert340+ }341+ // in is now positive342+ decNumberFromUInt32(dn, unsig);343+ if (in<0) dn->bits=DECNEG; // sign needed344+ return dn;345+ } // decNumberFromInt32346+347+decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {348+ Unit *up; // work pointer349+ decNumberZero(dn); // clean350+ if (uin==0) return dn; // [or decGetDigits bad call]351+ for (up=dn->lsu; uin>0; up++) {352+ *up=(Unit)(uin%(DECDPUNMAX+1));353+ uin=uin/(DECDPUNMAX+1);354+ }355+ dn->digits=decGetDigits(dn->lsu, up-dn->lsu);356+ return dn;357+ } // decNumberFromUInt32358+359+/* ------------------------------------------------------------------ */360+/* to-int32 -- conversion to Int or uInt */361+/* */362+/* dn is the decNumber to convert */363+/* set is the context for reporting errors */364+/* returns the converted decNumber, or 0 if Invalid is set */365+/* */366+/* Invalid is set if the decNumber does not have exponent==0 or if */367+/* it is a NaN, Infinite, or out-of-range. */368+/* ------------------------------------------------------------------ */369+Int decNumberToInt32(const decNumber *dn, decContext *set) {370+ #if DECCHECK371+ if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;372+ #endif373+374+ // special or too many digits, or bad exponent375+ if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad376+ else { // is a finite integer with 10 or fewer digits377+ Int d; // work378+ const Unit *up; // ..379+ uInt hi=0, lo; // ..380+ up=dn->lsu; // -> lsu381+ lo=*up; // get 1 to 9 digits382+ #if DECDPUN>1 // split to higher383+ hi=lo/10;384+ lo=lo%10;385+ #endif386+ up++;387+ // collect remaining Units, if any, into hi388+ for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];389+ // now low has the lsd, hi the remainder390+ if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?391+ // most-negative is a reprieve392+ if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;393+ // bad -- drop through394+ }395+ else { // in-range always396+ Int i=X10(hi)+lo;397+ if (dn->bits&DECNEG) return -i;398+ return i;399+ }400+ } // integer401+ decContextSetStatus(set, DEC_Invalid_operation); // [may not return]402+ return 0;403+ } // decNumberToInt32404+405+uInt decNumberToUInt32(const decNumber *dn, decContext *set) {406+ #if DECCHECK407+ if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;408+ #endif409+ // special or too many digits, or bad exponent, or negative (<0)410+ if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0411+ || (dn->bits&DECNEG && !ISZERO(dn))); // bad412+ else { // is a finite integer with 10 or fewer digits413+ Int d; // work414+ const Unit *up; // ..415+ uInt hi=0, lo; // ..416+ up=dn->lsu; // -> lsu417+ lo=*up; // get 1 to 9 digits418+ #if DECDPUN>1 // split to higher419+ hi=lo/10;420+ lo=lo%10;421+ #endif422+ up++;423+ // collect remaining Units, if any, into hi424+ for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];425+426+ // now low has the lsd, hi the remainder427+ if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible428+ else return X10(hi)+lo;429+ } // integer430+ decContextSetStatus(set, DEC_Invalid_operation); // [may not return]431+ return 0;432+ } // decNumberToUInt32433+434+/* ------------------------------------------------------------------ */435+/* to-scientific-string -- conversion to numeric string */436+/* to-engineering-string -- conversion to numeric string */437+/* */438+/* decNumberToString(dn, string); */439+/* decNumberToEngString(dn, string); */440+/* */441+/* dn is the decNumber to convert */442+/* string is the string where the result will be laid out */443+/* */444+/* string must be at least dn->digits+14 characters long */445+/* */446+/* No error is possible, and no status can be set. */447+/* ------------------------------------------------------------------ */448+char * decNumberToString(const decNumber *dn, char *string){449+ decToString(dn, string, 0);450+ return string;451+ } // DecNumberToString452+453+char * decNumberToEngString(const decNumber *dn, char *string){454+ decToString(dn, string, 1);455+ return string;456+ } // DecNumberToEngString457+458+/* ------------------------------------------------------------------ */459+/* to-number -- conversion from numeric string */460+/* */461+/* decNumberFromString -- convert string to decNumber */462+/* dn -- the number structure to fill */463+/* chars[] -- the string to convert ('\0' terminated) */464+/* set -- the context used for processing any error, */465+/* determining the maximum precision available */466+/* (set.digits), determining the maximum and minimum */467+/* exponent (set.emax and set.emin), determining if */468+/* extended values are allowed, and checking the */469+/* rounding mode if overflow occurs or rounding is */470+/* needed. */471+/* */472+/* The length of the coefficient and the size of the exponent are */473+/* checked by this routine, so the correct error (Underflow or */474+/* Overflow) can be reported or rounding applied, as necessary. */475+/* */476+/* If bad syntax is detected, the result will be a quiet NaN. */477+/* ------------------------------------------------------------------ */478+decNumber * decNumberFromString(decNumber *dn, const char chars[],479+ decContext *set) {480+ Int exponent=0; // working exponent [assume 0]481+ uByte bits=0; // working flags [assume +ve]482+ Unit *res; // where result will be built483+ Unit resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary484+ // [+9 allows for ln() constants]485+ Unit *allocres=NULL; // -> allocated result, iff allocated486+ Int d=0; // count of digits found in decimal part487+ const char *dotchar=NULL; // where dot was found488+ const char *cfirst=chars; // -> first character of decimal part489+ const char *last=NULL; // -> last digit of decimal part490+ const char *c; // work491+ Unit *up; // ..492+ #if DECDPUN>1493+ Int cut, out; // ..494+ #endif495+ Int residue; // rounding residue496+ uInt status=0; // error code497+498+ #if DECCHECK499+ if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))500+ return decNumberZero(dn);501+ #endif502+503+ do { // status & malloc protection504+ for (c=chars;; c++) { // -> input character505+ if (*c>='0' && *c<='9') { // test for Arabic digit506+ last=c;507+ d++; // count of real digits508+ continue; // still in decimal part509+ }510+ if (*c=='.' && dotchar==NULL) { // first '.'511+ dotchar=c; // record offset into decimal part512+ if (c==cfirst) cfirst++; // first digit must follow513+ continue;}514+ if (c==chars) { // first in string...515+ if (*c=='-') { // valid - sign516+ cfirst++;517+ bits=DECNEG;518+ continue;}519+ if (*c=='+') { // valid + sign520+ cfirst++;521+ continue;}522+ }523+ // *c is not a digit, or a valid +, -, or '.'524+ break;525+ } // c526+527+ if (last==NULL) { // no digits yet528+ status=DEC_Conversion_syntax;// assume the worst529+ if (*c=='\0') break; // and no more to come...530+ #if DECSUBSET531+ // if subset then infinities and NaNs are not allowed532+ if (!set->extended) break; // hopeless533+ #endif534+ // Infinities and NaNs are possible, here535+ if (dotchar!=NULL) break; // .. unless had a dot536+ decNumberZero(dn); // be optimistic537+ if (decBiStr(c, "infinity", "INFINITY")538+ || decBiStr(c, "inf", "INF")) {539+ dn->bits=bits | DECINF;540+ status=0; // is OK541+ break; // all done542+ }543+ // a NaN expected544+ // 2003.09.10 NaNs are now permitted to have a sign545+ dn->bits=bits | DECNAN; // assume simple NaN546+ if (*c=='s' || *c=='S') { // looks like an sNaN547+ c++;548+ dn->bits=bits | DECSNAN;549+ }550+ if (*c!='n' && *c!='N') break; // check caseless "NaN"551+ c++;552+ if (*c!='a' && *c!='A') break; // ..553+ c++;554+ if (*c!='n' && *c!='N') break; // ..555+ c++;556+ // now either nothing, or nnnn payload, expected557+ // -> start of integer and skip leading 0s [including plain 0]558+ for (cfirst=c; *cfirst=='0';) cfirst++;559+ if (*cfirst=='\0') { // "NaN" or "sNaN", maybe with all 0s560+ status=0; // it's good561+ break; // ..562+ }563+ // something other than 0s; setup last and d as usual [no dots]564+ for (c=cfirst;; c++, d++) {565+ if (*c<'0' || *c>'9') break; // test for Arabic digit566+ last=c;567+ }568+ if (*c!='\0') break; // not all digits569+ if (d>set->digits-1) {570+ // [NB: payload in a decNumber can be full length unless571+ // clamped, in which case can only be digits-1]572+ if (set->clamp) break;573+ if (d>set->digits) break;574+ } // too many digits?575+ // good; drop through to convert the integer to coefficient576+ status=0; // syntax is OK577+ bits=dn->bits; // for copy-back578+ } // last==NULL579+580+ else if (*c!='\0') { // more to process...581+ // had some digits; exponent is only valid sequence now582+ Flag nege; // 1=negative exponent583+ const char *firstexp; // -> first significant exponent digit584+ status=DEC_Conversion_syntax;// assume the worst585+ if (*c!='e' && *c!='E') break;586+ /* Found 'e' or 'E' -- now process explicit exponent */587+ // 1998.07.11: sign no longer required588+ nege=0;589+ c++; // to (possible) sign590+ if (*c=='-') {nege=1; c++;}591+ else if (*c=='+') c++;592+ if (*c=='\0') break;593+594+ for (; *c=='0' && *(c+1)!='\0';) c++; // strip insignificant zeros595+ firstexp=c; // save exponent digit place596+ for (; ;c++) {597+ if (*c<'0' || *c>'9') break; // not a digit598+ exponent=X10(exponent)+(Int)*c-(Int)'0';599+ } // c600+ // if not now on a '\0', *c must not be a digit601+ if (*c!='\0') break;602+603+ // (this next test must be after the syntax checks)604+ // if it was too long the exponent may have wrapped, so check605+ // carefully and set it to a certain overflow if wrap possible606+ if (c>=firstexp+9+1) {607+ if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;608+ // [up to 1999999999 is OK, for example 1E-1000000998]609+ }610+ if (nege) exponent=-exponent; // was negative611+ status=0; // is OK612+ } // stuff after digits613+614+ // Here when whole string has been inspected; syntax is good615+ // cfirst->first digit (never dot), last->last digit (ditto)616+617+ // strip leading zeros/dot [leave final 0 if all 0's]618+ if (*cfirst=='0') { // [cfirst has stepped over .]619+ for (c=cfirst; c<last; c++, cfirst++) {620+ if (*c=='.') continue; // ignore dots621+ if (*c!='0') break; // non-zero found622+ d--; // 0 stripped623+ } // c624+ #if DECSUBSET625+ // make a rapid exit for easy zeros if !extended626+ if (*cfirst=='0' && !set->extended) {627+ decNumberZero(dn); // clean result628+ break; // [could be return]629+ }630+ #endif631+ } // at least one leading 0632+633+ // Handle decimal point...634+ if (dotchar!=NULL && dotchar<last) // non-trailing '.' found?635+ exponent-=(last-dotchar); // adjust exponent636+ // [we can now ignore the .]637+638+ // OK, the digits string is good. Assemble in the decNumber, or in639+ // a temporary units array if rounding is needed640+ if (d<=set->digits) res=dn->lsu; // fits into supplied decNumber641+ else { // rounding needed642+ Int needbytes=D2U(d)*sizeof(Unit);// bytes needed643+ res=resbuff; // assume use local buffer644+ if (needbytes>(Int)sizeof(resbuff)) { // too big for local645+ allocres=(Unit *)malloc(needbytes);646+ if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}647+ res=allocres;648+ }649+ }650+ // res now -> number lsu, buffer, or allocated storage for Unit array651+652+ // Place the coefficient into the selected Unit array653+ // [this is often 70% of the cost of this function when DECDPUN>1]654+ #if DECDPUN>1655+ out=0; // accumulator656+ up=res+D2U(d)-1; // -> msu657+ cut=d-(up-res)*DECDPUN; // digits in top unit658+ for (c=cfirst;; c++) { // along the digits659+ if (*c=='.') continue; // ignore '.' [don't decrement cut]660+ out=X10(out)+(Int)*c-(Int)'0';661+ if (c==last) break; // done [never get to trailing '.']662+ cut--;663+ if (cut>0) continue; // more for this unit664+ *up=(Unit)out; // write unit665+ up--; // prepare for unit below..666+ cut=DECDPUN; // ..667+ out=0; // ..668+ } // c669+ *up=(Unit)out; // write lsu670+671+ #else672+ // DECDPUN==1673+ up=res; // -> lsu674+ for (c=last; c>=cfirst; c--) { // over each character, from least675+ if (*c=='.') continue; // ignore . [don't step up]676+ *up=(Unit)((Int)*c-(Int)'0');677+ up++;678+ } // c679+ #endif680+681+ dn->bits=bits;682+ dn->exponent=exponent;683+ dn->digits=d;684+685+ // if not in number (too long) shorten into the number686+ if (d>set->digits) {687+ residue=0;688+ decSetCoeff(dn, set, res, d, &residue, &status);689+ // always check for overflow or subnormal and round as needed690+ decFinalize(dn, set, &residue, &status);691+ }692+ else { // no rounding, but may still have overflow or subnormal693+ // [these tests are just for performance; finalize repeats them]694+ if ((dn->exponent-1<set->emin-dn->digits)695+ || (dn->exponent-1>set->emax-set->digits)) {696+ residue=0;697+ decFinalize(dn, set, &residue, &status);698+ }699+ }700+ // decNumberShow(dn);701+ } while(0); // [for break]702+703+ if (allocres!=NULL) free(allocres); // drop any storage used704+ if (status!=0) decStatus(dn, status, set);705+ return dn;706+ } /* decNumberFromString */707+708+/* ================================================================== */709+/* Operators */710+/* ================================================================== */711+712+/* ------------------------------------------------------------------ */713+/* decNumberAbs -- absolute value operator */714+/* */715+/* This computes C = abs(A) */716+/* */717+/* res is C, the result. C may be A */718+/* rhs is A */719+/* set is the context */720+/* */721+/* See also decNumberCopyAbs for a quiet bitwise version of this. */722+/* C must have space for set->digits digits. */723+/* ------------------------------------------------------------------ */724+/* This has the same effect as decNumberPlus unless A is negative, */725+/* in which case it has the same effect as decNumberMinus. */726+/* ------------------------------------------------------------------ */727+decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,728+ decContext *set) {729+ decNumber dzero; // for 0730+ uInt status=0; // accumulator731+732+ #if DECCHECK733+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;734+ #endif735+736+ decNumberZero(&dzero); // set 0737+ dzero.exponent=rhs->exponent; // [no coefficient expansion]738+ decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);739+ if (status!=0) decStatus(res, status, set);740+ #if DECCHECK741+ decCheckInexact(res, set);742+ #endif743+ return res;744+ } // decNumberAbs745+746+/* ------------------------------------------------------------------ */747+/* decNumberAdd -- add two Numbers */748+/* */749+/* This computes C = A + B */750+/* */751+/* res is C, the result. C may be A and/or B (e.g., X=X+X) */752+/* lhs is A */753+/* rhs is B */754+/* set is the context */755+/* */756+/* C must have space for set->digits digits. */757+/* ------------------------------------------------------------------ */758+/* This just calls the routine shared with Subtract */759+decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,760+ const decNumber *rhs, decContext *set) {761+ uInt status=0; // accumulator762+ decAddOp(res, lhs, rhs, set, 0, &status);763+ if (status!=0) decStatus(res, status, set);764+ #if DECCHECK765+ decCheckInexact(res, set);766+ #endif767+ return res;768+ } // decNumberAdd769+770+/* ------------------------------------------------------------------ */771+/* decNumberAnd -- AND two Numbers, digitwise */772+/* */773+/* This computes C = A & B */774+/* */775+/* res is C, the result. C may be A and/or B (e.g., X=X&X) */776+/* lhs is A */777+/* rhs is B */778+/* set is the context (used for result length and error report) */779+/* */780+/* C must have space for set->digits digits. */781+/* */782+/* Logical function restrictions apply (see above); a NaN is */783+/* returned with Invalid_operation if a restriction is violated. */784+/* ------------------------------------------------------------------ */785+decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,786+ const decNumber *rhs, decContext *set) {787+ const Unit *ua, *ub; // -> operands788+ const Unit *msua, *msub; // -> operand msus789+ Unit *uc, *msuc; // -> result and its msu790+ Int msudigs; // digits in res msu791+ #if DECCHECK792+ if (decCheckOperands(res, lhs, rhs, set)) return res;793+ #endif794+795+ if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)796+ || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {797+ decStatus(res, DEC_Invalid_operation, set);798+ return res;799+ }800+801+ // operands are valid802+ ua=lhs->lsu; // bottom-up803+ ub=rhs->lsu; // ..804+ uc=res->lsu; // ..805+ msua=ua+D2U(lhs->digits)-1; // -> msu of lhs806+ msub=ub+D2U(rhs->digits)-1; // -> msu of rhs807+ msuc=uc+D2U(set->digits)-1; // -> msu of result808+ msudigs=MSUDIGITS(set->digits); // [faster than remainder]809+ for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop810+ Unit a, b; // extract units811+ if (ua>msua) a=0;812+ else a=*ua;813+ if (ub>msub) b=0;814+ else b=*ub;815+ *uc=0; // can now write back816+ if (a|b) { // maybe 1 bits to examine817+ Int i, j;818+ *uc=0; // can now write back819+ // This loop could be unrolled and/or use BIN2BCD tables820+ for (i=0; i<DECDPUN; i++) {821+ if (a&b&1) *uc=*uc+(Unit)powers[i]; // effect AND822+ j=a%10;823+ a=a/10;824+ j|=b%10;825+ b=b/10;826+ if (j>1) {827+ decStatus(res, DEC_Invalid_operation, set);828+ return res;829+ }830+ if (uc==msuc && i==msudigs-1) break; // just did final digit831+ } // each digit832+ } // both OK833+ } // each unit834+ // [here uc-1 is the msu of the result]835+ res->digits=decGetDigits(res->lsu, uc-res->lsu);836+ res->exponent=0; // integer837+ res->bits=0; // sign=0838+ return res; // [no status to set]839+ } // decNumberAnd840+841+/* ------------------------------------------------------------------ */842+/* decNumberCompare -- compare two Numbers */843+/* */844+/* This computes C = A ? B */845+/* */846+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */847+/* lhs is A */848+/* rhs is B */849+/* set is the context */850+/* */851+/* C must have space for one digit (or NaN). */852+/* ------------------------------------------------------------------ */853+decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,854+ const decNumber *rhs, decContext *set) {855+ uInt status=0; // accumulator856+ decCompareOp(res, lhs, rhs, set, COMPARE, &status);857+ if (status!=0) decStatus(res, status, set);858+ return res;859+ } // decNumberCompare860+861+/* ------------------------------------------------------------------ */862+/* decNumberCompareSignal -- compare, signalling on all NaNs */863+/* */864+/* This computes C = A ? B */865+/* */866+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */867+/* lhs is A */868+/* rhs is B */869+/* set is the context */870+/* */871+/* C must have space for one digit (or NaN). */872+/* ------------------------------------------------------------------ */873+decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,874+ const decNumber *rhs, decContext *set) {875+ uInt status=0; // accumulator876+ decCompareOp(res, lhs, rhs, set, COMPSIG, &status);877+ if (status!=0) decStatus(res, status, set);878+ return res;879+ } // decNumberCompareSignal880+881+/* ------------------------------------------------------------------ */882+/* decNumberCompareTotal -- compare two Numbers, using total ordering */883+/* */884+/* This computes C = A ? B, under total ordering */885+/* */886+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */887+/* lhs is A */888+/* rhs is B */889+/* set is the context */890+/* */891+/* C must have space for one digit; the result will always be one of */892+/* -1, 0, or 1. */893+/* ------------------------------------------------------------------ */894+decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,895+ const decNumber *rhs, decContext *set) {896+ uInt status=0; // accumulator897+ decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);898+ if (status!=0) decStatus(res, status, set);899+ return res;900+ } // decNumberCompareTotal901+902+/* ------------------------------------------------------------------ */903+/* decNumberCompareTotalMag -- compare, total ordering of magnitudes */904+/* */905+/* This computes C = |A| ? |B|, under total ordering */906+/* */907+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */908+/* lhs is A */909+/* rhs is B */910+/* set is the context */911+/* */912+/* C must have space for one digit; the result will always be one of */913+/* -1, 0, or 1. */914+/* ------------------------------------------------------------------ */915+decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,916+ const decNumber *rhs, decContext *set) {917+ uInt status=0; // accumulator918+ uInt needbytes; // for space calculations919+ decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0920+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated921+ decNumber bufb[D2N(DECBUFFER+1)];922+ decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated923+ decNumber *a, *b; // temporary pointers924+925+ #if DECCHECK926+ if (decCheckOperands(res, lhs, rhs, set)) return res;927+ #endif928+929+ do { // protect allocated storage930+ // if either is negative, take a copy and absolute931+ if (decNumberIsNegative(lhs)) { // lhs<0932+ a=bufa;933+ needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);934+ if (needbytes>sizeof(bufa)) { // need malloc space935+ allocbufa=(decNumber *)malloc(needbytes);936+ if (allocbufa==NULL) { // hopeless -- abandon937+ status|=DEC_Insufficient_storage;938+ break;}939+ a=allocbufa; // use the allocated space940+ }941+ decNumberCopy(a, lhs); // copy content942+ a->bits&=~DECNEG; // .. and clear the sign943+ lhs=a; // use copy from here on944+ }945+ if (decNumberIsNegative(rhs)) { // rhs<0946+ b=bufb;947+ needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);948+ if (needbytes>sizeof(bufb)) { // need malloc space949+ allocbufb=(decNumber *)malloc(needbytes);950+ if (allocbufb==NULL) { // hopeless -- abandon951+ status|=DEC_Insufficient_storage;952+ break;}953+ b=allocbufb; // use the allocated space954+ }955+ decNumberCopy(b, rhs); // copy content956+ b->bits&=~DECNEG; // .. and clear the sign957+ rhs=b; // use copy from here on958+ }959+ decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);960+ } while(0); // end protected961+962+ if (allocbufa!=NULL) free(allocbufa); // drop any storage used963+ if (allocbufb!=NULL) free(allocbufb); // ..964+ if (status!=0) decStatus(res, status, set);965+ return res;966+ } // decNumberCompareTotalMag967+968+/* ------------------------------------------------------------------ */969+/* decNumberDivide -- divide one number by another */970+/* */971+/* This computes C = A / B */972+/* */973+/* res is C, the result. C may be A and/or B (e.g., X=X/X) */974+/* lhs is A */975+/* rhs is B */976+/* set is the context */977+/* */978+/* C must have space for set->digits digits. */979+/* ------------------------------------------------------------------ */980+decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,981+ const decNumber *rhs, decContext *set) {982+ uInt status=0; // accumulator983+ decDivideOp(res, lhs, rhs, set, DIVIDE, &status);984+ if (status!=0) decStatus(res, status, set);985+ #if DECCHECK986+ decCheckInexact(res, set);987+ #endif988+ return res;989+ } // decNumberDivide990+991+/* ------------------------------------------------------------------ */992+/* decNumberDivideInteger -- divide and return integer quotient */993+/* */994+/* This computes C = A # B, where # is the integer divide operator */995+/* */996+/* res is C, the result. C may be A and/or B (e.g., X=X#X) */997+/* lhs is A */998+/* rhs is B */999+/* set is the context */1000+/* */1001+/* C must have space for set->digits digits. */1002+/* ------------------------------------------------------------------ */1003+decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,1004+ const decNumber *rhs, decContext *set) {1005+ uInt status=0; // accumulator1006+ decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);1007+ if (status!=0) decStatus(res, status, set);1008+ return res;1009+ } // decNumberDivideInteger1010+1011+/* ------------------------------------------------------------------ */1012+/* decNumberExp -- exponentiation */1013+/* */1014+/* This computes C = exp(A) */1015+/* */1016+/* res is C, the result. C may be A */1017+/* rhs is A */1018+/* set is the context; note that rounding mode has no effect */1019+/* */1020+/* C must have space for set->digits digits. */1021+/* */1022+/* Mathematical function restrictions apply (see above); a NaN is */1023+/* returned with Invalid_operation if a restriction is violated. */1024+/* */1025+/* Finite results will always be full precision and Inexact, except */1026+/* when A is a zero or -Infinity (giving 1 or 0 respectively). */1027+/* */1028+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */1029+/* almost always be correctly rounded, but may be up to 1 ulp in */1030+/* error in rare cases. */1031+/* ------------------------------------------------------------------ */1032+/* This is a wrapper for decExpOp which can handle the slightly wider */1033+/* (double) range needed by Ln (which has to be able to calculate */1034+/* exp(-a) where a can be the tiniest number (Ntiny). */1035+/* ------------------------------------------------------------------ */1036+decNumber * decNumberExp(decNumber *res, const decNumber *rhs,1037+ decContext *set) {1038+ uInt status=0; // accumulator1039+ #if DECSUBSET1040+ decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated1041+ #endif1042+1043+ #if DECCHECK1044+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1045+ #endif1046+1047+ // Check restrictions; these restrictions ensure that if h=8 (see1048+ // decExpOp) then the result will either overflow or underflow to 0.1049+ // Other math functions restrict the input range, too, for inverses.1050+ // If not violated then carry out the operation.1051+ if (!decCheckMath(rhs, set, &status)) do { // protect allocation1052+ #if DECSUBSET1053+ if (!set->extended) {1054+ // reduce operand and set lostDigits status, as needed1055+ if (rhs->digits>set->digits) {1056+ allocrhs=decRoundOperand(rhs, set, &status);1057+ if (allocrhs==NULL) break;1058+ rhs=allocrhs;1059+ }1060+ }1061+ #endif1062+ decExpOp(res, rhs, set, &status);1063+ } while(0); // end protected1064+1065+ #if DECSUBSET1066+ if (allocrhs !=NULL) free(allocrhs); // drop any storage used1067+ #endif1068+ // apply significant status1069+ if (status!=0) decStatus(res, status, set);1070+ #if DECCHECK1071+ decCheckInexact(res, set);1072+ #endif1073+ return res;1074+ } // decNumberExp1075+1076+/* ------------------------------------------------------------------ */1077+/* decNumberFMA -- fused multiply add */1078+/* */1079+/* This computes D = (A * B) + C with only one rounding */1080+/* */1081+/* res is D, the result. D may be A or B or C (e.g., X=FMA(X,X,X)) */1082+/* lhs is A */1083+/* rhs is B */1084+/* fhs is C [far hand side] */1085+/* set is the context */1086+/* */1087+/* Mathematical function restrictions apply (see above); a NaN is */1088+/* returned with Invalid_operation if a restriction is violated. */1089+/* */1090+/* C must have space for set->digits digits. */1091+/* ------------------------------------------------------------------ */1092+decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,1093+ const decNumber *rhs, const decNumber *fhs,1094+ decContext *set) {1095+ uInt status=0; // accumulator1096+ decContext dcmul; // context for the multiplication1097+ uInt needbytes; // for space calculations1098+ decNumber bufa[D2N(DECBUFFER*2+1)];1099+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated1100+ decNumber *acc; // accumulator pointer1101+ decNumber dzero; // work1102+1103+ #if DECCHECK1104+ if (decCheckOperands(res, lhs, rhs, set)) return res;1105+ if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;1106+ #endif1107+1108+ do { // protect allocated storage1109+ #if DECSUBSET1110+ if (!set->extended) { // [undefined if subset]1111+ status|=DEC_Invalid_operation;1112+ break;}1113+ #endif1114+ // Check math restrictions [these ensure no overflow or underflow]1115+ if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))1116+ || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))1117+ || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;1118+ // set up context for multiply1119+ dcmul=*set;1120+ dcmul.digits=lhs->digits+rhs->digits; // just enough1121+ // [The above may be an over-estimate for subset arithmetic, but that's OK]1122+ dcmul.emax=DEC_MAX_EMAX; // effectively unbounded ..1123+ dcmul.emin=DEC_MIN_EMIN; // [thanks to Math restrictions]1124+ // set up decNumber space to receive the result of the multiply1125+ acc=bufa; // may fit1126+ needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);1127+ if (needbytes>sizeof(bufa)) { // need malloc space1128+ allocbufa=(decNumber *)malloc(needbytes);1129+ if (allocbufa==NULL) { // hopeless -- abandon1130+ status|=DEC_Insufficient_storage;1131+ break;}1132+ acc=allocbufa; // use the allocated space1133+ }1134+ // multiply with extended range and necessary precision1135+ //printf("emin=%ld\n", dcmul.emin);1136+ decMultiplyOp(acc, lhs, rhs, &dcmul, &status);1137+ // Only Invalid operation (from sNaN or Inf * 0) is possible in1138+ // status; if either is seen than ignore fhs (in case it is1139+ // another sNaN) and set acc to NaN unless we had an sNaN1140+ // [decMultiplyOp leaves that to caller]1141+ // Note sNaN has to go through addOp to shorten payload if1142+ // necessary1143+ if ((status&DEC_Invalid_operation)!=0) {1144+ if (!(status&DEC_sNaN)) { // but be true invalid1145+ decNumberZero(res); // acc not yet set1146+ res->bits=DECNAN;1147+ break;1148+ }1149+ decNumberZero(&dzero); // make 0 (any non-NaN would do)1150+ fhs=&dzero; // use that1151+ }1152+ #if DECCHECK1153+ else { // multiply was OK1154+ if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);1155+ }1156+ #endif1157+ // add the third operand and result -> res, and all is done1158+ decAddOp(res, acc, fhs, set, 0, &status);1159+ } while(0); // end protected1160+1161+ if (allocbufa!=NULL) free(allocbufa); // drop any storage used1162+ if (status!=0) decStatus(res, status, set);1163+ #if DECCHECK1164+ decCheckInexact(res, set);1165+ #endif1166+ return res;1167+ } // decNumberFMA1168+1169+/* ------------------------------------------------------------------ */1170+/* decNumberInvert -- invert a Number, digitwise */1171+/* */1172+/* This computes C = ~A */1173+/* */1174+/* res is C, the result. C may be A (e.g., X=~X) */1175+/* rhs is A */1176+/* set is the context (used for result length and error report) */1177+/* */1178+/* C must have space for set->digits digits. */1179+/* */1180+/* Logical function restrictions apply (see above); a NaN is */1181+/* returned with Invalid_operation if a restriction is violated. */1182+/* ------------------------------------------------------------------ */1183+decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,1184+ decContext *set) {1185+ const Unit *ua, *msua; // -> operand and its msu1186+ Unit *uc, *msuc; // -> result and its msu1187+ Int msudigs; // digits in res msu1188+ #if DECCHECK1189+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1190+ #endif1191+1192+ if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {1193+ decStatus(res, DEC_Invalid_operation, set);1194+ return res;1195+ }1196+ // operand is valid1197+ ua=rhs->lsu; // bottom-up1198+ uc=res->lsu; // ..1199+ msua=ua+D2U(rhs->digits)-1; // -> msu of rhs1200+ msuc=uc+D2U(set->digits)-1; // -> msu of result1201+ msudigs=MSUDIGITS(set->digits); // [faster than remainder]1202+ for (; uc<=msuc; ua++, uc++) { // Unit loop1203+ Unit a; // extract unit1204+ Int i, j; // work1205+ if (ua>msua) a=0;1206+ else a=*ua;1207+ *uc=0; // can now write back1208+ // always need to examine all bits in rhs1209+ // This loop could be unrolled and/or use BIN2BCD tables1210+ for (i=0; i<DECDPUN; i++) {1211+ if ((~a)&1) *uc=*uc+(Unit)powers[i]; // effect INVERT1212+ j=a%10;1213+ a=a/10;1214+ if (j>1) {1215+ decStatus(res, DEC_Invalid_operation, set);1216+ return res;1217+ }1218+ if (uc==msuc && i==msudigs-1) break; // just did final digit1219+ } // each digit1220+ } // each unit1221+ // [here uc-1 is the msu of the result]1222+ res->digits=decGetDigits(res->lsu, uc-res->lsu);1223+ res->exponent=0; // integer1224+ res->bits=0; // sign=01225+ return res; // [no status to set]1226+ } // decNumberInvert1227+1228+/* ------------------------------------------------------------------ */1229+/* decNumberLn -- natural logarithm */1230+/* */1231+/* This computes C = ln(A) */1232+/* */1233+/* res is C, the result. C may be A */1234+/* rhs is A */1235+/* set is the context; note that rounding mode has no effect */1236+/* */1237+/* C must have space for set->digits digits. */1238+/* */1239+/* Notable cases: */1240+/* A<0 -> Invalid */1241+/* A=0 -> -Infinity (Exact) */1242+/* A=+Infinity -> +Infinity (Exact) */1243+/* A=1 exactly -> 0 (Exact) */1244+/* */1245+/* Mathematical function restrictions apply (see above); a NaN is */1246+/* returned with Invalid_operation if a restriction is violated. */1247+/* */1248+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */1249+/* almost always be correctly rounded, but may be up to 1 ulp in */1250+/* error in rare cases. */1251+/* ------------------------------------------------------------------ */1252+/* This is a wrapper for decLnOp which can handle the slightly wider */1253+/* (+11) range needed by Ln, Log10, etc. (which may have to be able */1254+/* to calculate at p+e+2). */1255+/* ------------------------------------------------------------------ */1256+decNumber * decNumberLn(decNumber *res, const decNumber *rhs,1257+ decContext *set) {1258+ uInt status=0; // accumulator1259+ #if DECSUBSET1260+ decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated1261+ #endif1262+1263+ #if DECCHECK1264+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1265+ #endif1266+1267+ // Check restrictions; this is a math function; if not violated1268+ // then carry out the operation.1269+ if (!decCheckMath(rhs, set, &status)) do { // protect allocation1270+ #if DECSUBSET1271+ if (!set->extended) {1272+ // reduce operand and set lostDigits status, as needed1273+ if (rhs->digits>set->digits) {1274+ allocrhs=decRoundOperand(rhs, set, &status);1275+ if (allocrhs==NULL) break;1276+ rhs=allocrhs;1277+ }1278+ // special check in subset for rhs=01279+ if (ISZERO(rhs)) { // +/- zeros -> error1280+ status|=DEC_Invalid_operation;1281+ break;}1282+ } // extended=01283+ #endif1284+ decLnOp(res, rhs, set, &status);1285+ } while(0); // end protected1286+1287+ #if DECSUBSET1288+ if (allocrhs !=NULL) free(allocrhs); // drop any storage used1289+ #endif1290+ // apply significant status1291+ if (status!=0) decStatus(res, status, set);1292+ #if DECCHECK1293+ decCheckInexact(res, set);1294+ #endif1295+ return res;1296+ } // decNumberLn1297+1298+/* ------------------------------------------------------------------ */1299+/* decNumberLogB - get adjusted exponent, by 754 rules */1300+/* */1301+/* This computes C = adjustedexponent(A) */1302+/* */1303+/* res is C, the result. C may be A */1304+/* rhs is A */1305+/* set is the context, used only for digits and status */1306+/* */1307+/* For an unrounded result, digits may need to be 10 (A might have */1308+/* 10**9 digits and an exponent of +999999999, or one digit and an */1309+/* exponent of -1999999999). */1310+/* */1311+/* This returns the adjusted exponent of A after (in theory) padding */1312+/* with zeros on the right to set->digits digits while keeping the */1313+/* same value. The exponent is not limited by emin/emax. */1314+/* */1315+/* Notable cases: */1316+/* A<0 -> Use |A| */1317+/* A=0 -> -Infinity (Division by zero) */1318+/* A=Infinite -> +Infinity (Exact) */1319+/* A=1 exactly -> 0 (Exact) */1320+/* NaNs are propagated as usual */1321+/* ------------------------------------------------------------------ */1322+decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,1323+ decContext *set) {1324+ uInt status=0; // accumulator1325+1326+ #if DECCHECK1327+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1328+ #endif1329+1330+ // NaNs as usual; Infinities return +Infinity; 0->oops1331+ if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);1332+ else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);1333+ else if (decNumberIsZero(rhs)) {1334+ decNumberZero(res); // prepare for Infinity1335+ res->bits=DECNEG|DECINF; // -Infinity1336+ status|=DEC_Division_by_zero; // as per 7541337+ }1338+ else { // finite non-zero1339+ Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent1340+ if (set->digits>=10) decNumberFromInt32(res, ae); // lay it out1341+ else {1342+ decNumber buft[D2N(10)]; // temporary number1343+ decNumber *t=buft; // ..1344+ decNumberFromInt32(t, ae); // lay it out1345+ decNumberPlus(res, t, set); // round as necessary1346+ }1347+ }1348+1349+ if (status!=0) decStatus(res, status, set);1350+ return res;1351+ } // decNumberLogB1352+1353+/* ------------------------------------------------------------------ */1354+/* decNumberLog10 -- logarithm in base 10 */1355+/* */1356+/* This computes C = log10(A) */1357+/* */1358+/* res is C, the result. C may be A */1359+/* rhs is A */1360+/* set is the context; note that rounding mode has no effect */1361+/* */1362+/* C must have space for set->digits digits. */1363+/* */1364+/* Notable cases: */1365+/* A<0 -> Invalid */1366+/* A=0 -> -Infinity (Exact) */1367+/* A=+Infinity -> +Infinity (Exact) */1368+/* A=10**n (if n is an integer) -> n (Exact) */1369+/* */1370+/* Mathematical function restrictions apply (see above); a NaN is */1371+/* returned with Invalid_operation if a restriction is violated. */1372+/* */1373+/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will */1374+/* almost always be correctly rounded, but may be up to 1 ulp in */1375+/* error in rare cases. */1376+/* ------------------------------------------------------------------ */1377+/* This calculates ln(A)/ln(10) using appropriate precision. For */1378+/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the */1379+/* requested digits and t is the number of digits in the exponent */1380+/* (maximum 6). For ln(10) it is p + 3; this is often handled by the */1381+/* fastpath in decLnOp. The final division is done to the requested */1382+/* precision. */1383+/* ------------------------------------------------------------------ */1384+decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,1385+ decContext *set) {1386+ uInt status=0, ignore=0; // status accumulators1387+ uInt needbytes; // for space calculations1388+ Int p; // working precision1389+ Int t; // digits in exponent of A1390+1391+ // buffers for a and b working decimals1392+ // (adjustment calculator, same size)1393+ decNumber bufa[D2N(DECBUFFER+2)];1394+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated1395+ decNumber *a=bufa; // temporary a1396+ decNumber bufb[D2N(DECBUFFER+2)];1397+ decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated1398+ decNumber *b=bufb; // temporary b1399+ decNumber bufw[D2N(10)]; // working 2-10 digit number1400+ decNumber *w=bufw; // ..1401+ #if DECSUBSET1402+ decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated1403+ #endif1404+1405+ decContext aset; // working context1406+1407+ #if DECCHECK1408+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1409+ #endif1410+1411+ // Check restrictions; this is a math function; if not violated1412+ // then carry out the operation.1413+ if (!decCheckMath(rhs, set, &status)) do { // protect malloc1414+ #if DECSUBSET1415+ if (!set->extended) {1416+ // reduce operand and set lostDigits status, as needed1417+ if (rhs->digits>set->digits) {1418+ allocrhs=decRoundOperand(rhs, set, &status);1419+ if (allocrhs==NULL) break;1420+ rhs=allocrhs;1421+ }1422+ // special check in subset for rhs=01423+ if (ISZERO(rhs)) { // +/- zeros -> error1424+ status|=DEC_Invalid_operation;1425+ break;}1426+ } // extended=01427+ #endif1428+1429+ decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context1430+1431+ // handle exact powers of 10; only check if +ve finite1432+ if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {1433+ Int residue=0; // (no residue)1434+ uInt copystat=0; // clean status1435+1436+ // round to a single digit...1437+ aset.digits=1;1438+ decCopyFit(w, rhs, &aset, &residue, ©stat); // copy & shorten1439+ // if exact and the digit is 1, rhs is a power of 101440+ if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {1441+ // the exponent, conveniently, is the power of 10; making1442+ // this the result needs a little care as it might not fit,1443+ // so first convert it into the working number, and then move1444+ // to res1445+ decNumberFromInt32(w, w->exponent);1446+ residue=0;1447+ decCopyFit(res, w, set, &residue, &status); // copy & round1448+ decFinish(res, set, &residue, &status); // cleanup/set flags1449+ break;1450+ } // not a power of 101451+ } // not a candidate for exact1452+1453+ // simplify the information-content calculation to use 'total1454+ // number of digits in a, including exponent' as compared to the1455+ // requested digits, as increasing this will only rarely cost an1456+ // iteration in ln(a) anyway1457+ t=6; // it can never be >61458+1459+ // allocate space when needed...1460+ p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;1461+ needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);1462+ if (needbytes>sizeof(bufa)) { // need malloc space1463+ allocbufa=(decNumber *)malloc(needbytes);1464+ if (allocbufa==NULL) { // hopeless -- abandon1465+ status|=DEC_Insufficient_storage;1466+ break;}1467+ a=allocbufa; // use the allocated space1468+ }1469+ aset.digits=p; // as calculated1470+ aset.emax=DEC_MAX_MATH; // usual bounds1471+ aset.emin=-DEC_MAX_MATH; // ..1472+ aset.clamp=0; // and no concrete format1473+ decLnOp(a, rhs, &aset, &status); // a=ln(rhs)1474+1475+ // skip the division if the result so far is infinite, NaN, or1476+ // zero, or there was an error; note NaN from sNaN needs copy1477+ if (status&DEC_NaNs && !(status&DEC_sNaN)) break;1478+ if (a->bits&DECSPECIAL || ISZERO(a)) {1479+ decNumberCopy(res, a); // [will fit]1480+ break;}1481+1482+ // for ln(10) an extra 3 digits of precision are needed1483+ p=set->digits+3;1484+ needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);1485+ if (needbytes>sizeof(bufb)) { // need malloc space1486+ allocbufb=(decNumber *)malloc(needbytes);1487+ if (allocbufb==NULL) { // hopeless -- abandon1488+ status|=DEC_Insufficient_storage;1489+ break;}1490+ b=allocbufb; // use the allocated space1491+ }1492+ decNumberZero(w); // set up 10...1493+ #if DECDPUN==11494+ w->lsu[1]=1; w->lsu[0]=0; // ..1495+ #else1496+ w->lsu[0]=10; // ..1497+ #endif1498+ w->digits=2; // ..1499+1500+ aset.digits=p;1501+ decLnOp(b, w, &aset, &ignore); // b=ln(10)1502+1503+ aset.digits=set->digits; // for final divide1504+ decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result1505+ } while(0); // [for break]1506+1507+ if (allocbufa!=NULL) free(allocbufa); // drop any storage used1508+ if (allocbufb!=NULL) free(allocbufb); // ..1509+ #if DECSUBSET1510+ if (allocrhs !=NULL) free(allocrhs); // ..1511+ #endif1512+ // apply significant status1513+ if (status!=0) decStatus(res, status, set);1514+ #if DECCHECK1515+ decCheckInexact(res, set);1516+ #endif1517+ return res;1518+ } // decNumberLog101519+1520+/* ------------------------------------------------------------------ */1521+/* decNumberMax -- compare two Numbers and return the maximum */1522+/* */1523+/* This computes C = A ? B, returning the maximum by 754 rules */1524+/* */1525+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */1526+/* lhs is A */1527+/* rhs is B */1528+/* set is the context */1529+/* */1530+/* C must have space for set->digits digits. */1531+/* ------------------------------------------------------------------ */1532+decNumber * decNumberMax(decNumber *res, const decNumber *lhs,1533+ const decNumber *rhs, decContext *set) {1534+ uInt status=0; // accumulator1535+ decCompareOp(res, lhs, rhs, set, COMPMAX, &status);1536+ if (status!=0) decStatus(res, status, set);1537+ #if DECCHECK1538+ decCheckInexact(res, set);1539+ #endif1540+ return res;1541+ } // decNumberMax1542+1543+/* ------------------------------------------------------------------ */1544+/* decNumberMaxMag -- compare and return the maximum by magnitude */1545+/* */1546+/* This computes C = A ? B, returning the maximum by 754 rules */1547+/* */1548+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */1549+/* lhs is A */1550+/* rhs is B */1551+/* set is the context */1552+/* */1553+/* C must have space for set->digits digits. */1554+/* ------------------------------------------------------------------ */1555+decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,1556+ const decNumber *rhs, decContext *set) {1557+ uInt status=0; // accumulator1558+ decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);1559+ if (status!=0) decStatus(res, status, set);1560+ #if DECCHECK1561+ decCheckInexact(res, set);1562+ #endif1563+ return res;1564+ } // decNumberMaxMag1565+1566+/* ------------------------------------------------------------------ */1567+/* decNumberMin -- compare two Numbers and return the minimum */1568+/* */1569+/* This computes C = A ? B, returning the minimum by 754 rules */1570+/* */1571+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */1572+/* lhs is A */1573+/* rhs is B */1574+/* set is the context */1575+/* */1576+/* C must have space for set->digits digits. */1577+/* ------------------------------------------------------------------ */1578+decNumber * decNumberMin(decNumber *res, const decNumber *lhs,1579+ const decNumber *rhs, decContext *set) {1580+ uInt status=0; // accumulator1581+ decCompareOp(res, lhs, rhs, set, COMPMIN, &status);1582+ if (status!=0) decStatus(res, status, set);1583+ #if DECCHECK1584+ decCheckInexact(res, set);1585+ #endif1586+ return res;1587+ } // decNumberMin1588+1589+/* ------------------------------------------------------------------ */1590+/* decNumberMinMag -- compare and return the minimum by magnitude */1591+/* */1592+/* This computes C = A ? B, returning the minimum by 754 rules */1593+/* */1594+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */1595+/* lhs is A */1596+/* rhs is B */1597+/* set is the context */1598+/* */1599+/* C must have space for set->digits digits. */1600+/* ------------------------------------------------------------------ */1601+decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,1602+ const decNumber *rhs, decContext *set) {1603+ uInt status=0; // accumulator1604+ decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);1605+ if (status!=0) decStatus(res, status, set);1606+ #if DECCHECK1607+ decCheckInexact(res, set);1608+ #endif1609+ return res;1610+ } // decNumberMinMag1611+1612+/* ------------------------------------------------------------------ */1613+/* decNumberMinus -- prefix minus operator */1614+/* */1615+/* This computes C = 0 - A */1616+/* */1617+/* res is C, the result. C may be A */1618+/* rhs is A */1619+/* set is the context */1620+/* */1621+/* See also decNumberCopyNegate for a quiet bitwise version of this. */1622+/* C must have space for set->digits digits. */1623+/* ------------------------------------------------------------------ */1624+/* Simply use AddOp for the subtract, which will do the necessary. */1625+/* ------------------------------------------------------------------ */1626+decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,1627+ decContext *set) {1628+ decNumber dzero;1629+ uInt status=0; // accumulator1630+1631+ #if DECCHECK1632+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1633+ #endif1634+1635+ decNumberZero(&dzero); // make 01636+ dzero.exponent=rhs->exponent; // [no coefficient expansion]1637+ decAddOp(res, &dzero, rhs, set, DECNEG, &status);1638+ if (status!=0) decStatus(res, status, set);1639+ #if DECCHECK1640+ decCheckInexact(res, set);1641+ #endif1642+ return res;1643+ } // decNumberMinus1644+1645+/* ------------------------------------------------------------------ */1646+/* decNumberNextMinus -- next towards -Infinity */1647+/* */1648+/* This computes C = A - infinitesimal, rounded towards -Infinity */1649+/* */1650+/* res is C, the result. C may be A */1651+/* rhs is A */1652+/* set is the context */1653+/* */1654+/* This is a generalization of 754 NextDown. */1655+/* ------------------------------------------------------------------ */1656+decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,1657+ decContext *set) {1658+ decNumber dtiny; // constant1659+ decContext workset=*set; // work1660+ uInt status=0; // accumulator1661+ #if DECCHECK1662+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1663+ #endif1664+1665+ // +Infinity is the special case1666+ if ((rhs->bits&(DECINF|DECNEG))==DECINF) {1667+ decSetMaxValue(res, set); // is +ve1668+ // there is no status to set1669+ return res;1670+ }1671+ decNumberZero(&dtiny); // start with 01672+ dtiny.lsu[0]=1; // make number that is ..1673+ dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest1674+ workset.round=DEC_ROUND_FLOOR;1675+ decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);1676+ status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please1677+ if (status!=0) decStatus(res, status, set);1678+ return res;1679+ } // decNumberNextMinus1680+1681+/* ------------------------------------------------------------------ */1682+/* decNumberNextPlus -- next towards +Infinity */1683+/* */1684+/* This computes C = A + infinitesimal, rounded towards +Infinity */1685+/* */1686+/* res is C, the result. C may be A */1687+/* rhs is A */1688+/* set is the context */1689+/* */1690+/* This is a generalization of 754 NextUp. */1691+/* ------------------------------------------------------------------ */1692+decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,1693+ decContext *set) {1694+ decNumber dtiny; // constant1695+ decContext workset=*set; // work1696+ uInt status=0; // accumulator1697+ #if DECCHECK1698+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1699+ #endif1700+1701+ // -Infinity is the special case1702+ if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {1703+ decSetMaxValue(res, set);1704+ res->bits=DECNEG; // negative1705+ // there is no status to set1706+ return res;1707+ }1708+ decNumberZero(&dtiny); // start with 01709+ dtiny.lsu[0]=1; // make number that is ..1710+ dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest1711+ workset.round=DEC_ROUND_CEILING;1712+ decAddOp(res, rhs, &dtiny, &workset, 0, &status);1713+ status&=DEC_Invalid_operation|DEC_sNaN; // only sNaN Invalid please1714+ if (status!=0) decStatus(res, status, set);1715+ return res;1716+ } // decNumberNextPlus1717+1718+/* ------------------------------------------------------------------ */1719+/* decNumberNextToward -- next towards rhs */1720+/* */1721+/* This computes C = A +/- infinitesimal, rounded towards */1722+/* +/-Infinity in the direction of B, as per 754-1985 nextafter */1723+/* modified during revision but dropped from 754-2008. */1724+/* */1725+/* res is C, the result. C may be A or B. */1726+/* lhs is A */1727+/* rhs is B */1728+/* set is the context */1729+/* */1730+/* This is a generalization of 754-1985 NextAfter. */1731+/* ------------------------------------------------------------------ */1732+decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,1733+ const decNumber *rhs, decContext *set) {1734+ decNumber dtiny; // constant1735+ decContext workset=*set; // work1736+ Int result; // ..1737+ uInt status=0; // accumulator1738+ #if DECCHECK1739+ if (decCheckOperands(res, lhs, rhs, set)) return res;1740+ #endif1741+1742+ if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {1743+ decNaNs(res, lhs, rhs, set, &status);1744+ }1745+ else { // Is numeric, so no chance of sNaN Invalid, etc.1746+ result=decCompare(lhs, rhs, 0); // sign matters1747+ if (result==BADINT) status|=DEC_Insufficient_storage; // rare1748+ else { // valid compare1749+ if (result==0) decNumberCopySign(res, lhs, rhs); // easy1750+ else { // differ: need NextPlus or NextMinus1751+ uByte sub; // add or subtract1752+ if (result<0) { // lhs<rhs, do nextplus1753+ // -Infinity is the special case1754+ if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {1755+ decSetMaxValue(res, set);1756+ res->bits=DECNEG; // negative1757+ return res; // there is no status to set1758+ }1759+ workset.round=DEC_ROUND_CEILING;1760+ sub=0; // add, please1761+ } // plus1762+ else { // lhs>rhs, do nextminus1763+ // +Infinity is the special case1764+ if ((lhs->bits&(DECINF|DECNEG))==DECINF) {1765+ decSetMaxValue(res, set);1766+ return res; // there is no status to set1767+ }1768+ workset.round=DEC_ROUND_FLOOR;1769+ sub=DECNEG; // subtract, please1770+ } // minus1771+ decNumberZero(&dtiny); // start with 01772+ dtiny.lsu[0]=1; // make number that is ..1773+ dtiny.exponent=DEC_MIN_EMIN-1; // .. smaller than tiniest1774+ decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -1775+ // turn off exceptions if the result is a normal number1776+ // (including Nmin), otherwise let all status through1777+ if (decNumberIsNormal(res, set)) status=0;1778+ } // unequal1779+ } // compare OK1780+ } // numeric1781+ if (status!=0) decStatus(res, status, set);1782+ return res;1783+ } // decNumberNextToward1784+1785+/* ------------------------------------------------------------------ */1786+/* decNumberOr -- OR two Numbers, digitwise */1787+/* */1788+/* This computes C = A | B */1789+/* */1790+/* res is C, the result. C may be A and/or B (e.g., X=X|X) */1791+/* lhs is A */1792+/* rhs is B */1793+/* set is the context (used for result length and error report) */1794+/* */1795+/* C must have space for set->digits digits. */1796+/* */1797+/* Logical function restrictions apply (see above); a NaN is */1798+/* returned with Invalid_operation if a restriction is violated. */1799+/* ------------------------------------------------------------------ */1800+decNumber * decNumberOr(decNumber *res, const decNumber *lhs,1801+ const decNumber *rhs, decContext *set) {1802+ const Unit *ua, *ub; // -> operands1803+ const Unit *msua, *msub; // -> operand msus1804+ Unit *uc, *msuc; // -> result and its msu1805+ Int msudigs; // digits in res msu1806+ #if DECCHECK1807+ if (decCheckOperands(res, lhs, rhs, set)) return res;1808+ #endif1809+1810+ if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)1811+ || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {1812+ decStatus(res, DEC_Invalid_operation, set);1813+ return res;1814+ }1815+ // operands are valid1816+ ua=lhs->lsu; // bottom-up1817+ ub=rhs->lsu; // ..1818+ uc=res->lsu; // ..1819+ msua=ua+D2U(lhs->digits)-1; // -> msu of lhs1820+ msub=ub+D2U(rhs->digits)-1; // -> msu of rhs1821+ msuc=uc+D2U(set->digits)-1; // -> msu of result1822+ msudigs=MSUDIGITS(set->digits); // [faster than remainder]1823+ for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop1824+ Unit a, b; // extract units1825+ if (ua>msua) a=0;1826+ else a=*ua;1827+ if (ub>msub) b=0;1828+ else b=*ub;1829+ *uc=0; // can now write back1830+ if (a|b) { // maybe 1 bits to examine1831+ Int i, j;1832+ // This loop could be unrolled and/or use BIN2BCD tables1833+ for (i=0; i<DECDPUN; i++) {1834+ if ((a|b)&1) *uc=*uc+(Unit)powers[i]; // effect OR1835+ j=a%10;1836+ a=a/10;1837+ j|=b%10;1838+ b=b/10;1839+ if (j>1) {1840+ decStatus(res, DEC_Invalid_operation, set);1841+ return res;1842+ }1843+ if (uc==msuc && i==msudigs-1) break; // just did final digit1844+ } // each digit1845+ } // non-zero1846+ } // each unit1847+ // [here uc-1 is the msu of the result]1848+ res->digits=decGetDigits(res->lsu, uc-res->lsu);1849+ res->exponent=0; // integer1850+ res->bits=0; // sign=01851+ return res; // [no status to set]1852+ } // decNumberOr1853+1854+/* ------------------------------------------------------------------ */1855+/* decNumberPlus -- prefix plus operator */1856+/* */1857+/* This computes C = 0 + A */1858+/* */1859+/* res is C, the result. C may be A */1860+/* rhs is A */1861+/* set is the context */1862+/* */1863+/* See also decNumberCopy for a quiet bitwise version of this. */1864+/* C must have space for set->digits digits. */1865+/* ------------------------------------------------------------------ */1866+/* This simply uses AddOp; Add will take fast path after preparing A. */1867+/* Performance is a concern here, as this routine is often used to */1868+/* check operands and apply rounding and overflow/underflow testing. */1869+/* ------------------------------------------------------------------ */1870+decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,1871+ decContext *set) {1872+ decNumber dzero;1873+ uInt status=0; // accumulator1874+ #if DECCHECK1875+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;1876+ #endif1877+1878+ decNumberZero(&dzero); // make 01879+ dzero.exponent=rhs->exponent; // [no coefficient expansion]1880+ decAddOp(res, &dzero, rhs, set, 0, &status);1881+ if (status!=0) decStatus(res, status, set);1882+ #if DECCHECK1883+ decCheckInexact(res, set);1884+ #endif1885+ return res;1886+ } // decNumberPlus1887+1888+/* ------------------------------------------------------------------ */1889+/* decNumberMultiply -- multiply two Numbers */1890+/* */1891+/* This computes C = A x B */1892+/* */1893+/* res is C, the result. C may be A and/or B (e.g., X=X+X) */1894+/* lhs is A */1895+/* rhs is B */1896+/* set is the context */1897+/* */1898+/* C must have space for set->digits digits. */1899+/* ------------------------------------------------------------------ */1900+decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,1901+ const decNumber *rhs, decContext *set) {1902+ uInt status=0; // accumulator1903+ decMultiplyOp(res, lhs, rhs, set, &status);1904+ if (status!=0) decStatus(res, status, set);1905+ #if DECCHECK1906+ decCheckInexact(res, set);1907+ #endif1908+ return res;1909+ } // decNumberMultiply1910+1911+/* ------------------------------------------------------------------ */1912+/* decNumberPower -- raise a number to a power */1913+/* */1914+/* This computes C = A ** B */1915+/* */1916+/* res is C, the result. C may be A and/or B (e.g., X=X**X) */1917+/* lhs is A */1918+/* rhs is B */1919+/* set is the context */1920+/* */1921+/* C must have space for set->digits digits. */1922+/* */1923+/* Mathematical function restrictions apply (see above); a NaN is */1924+/* returned with Invalid_operation if a restriction is violated. */1925+/* */1926+/* However, if 1999999997<=B<=999999999 and B is an integer then the */1927+/* restrictions on A and the context are relaxed to the usual bounds, */1928+/* for compatibility with the earlier (integer power only) version */1929+/* of this function. */1930+/* */1931+/* When B is an integer, the result may be exact, even if rounded. */1932+/* */1933+/* The final result is rounded according to the context; it will */1934+/* almost always be correctly rounded, but may be up to 1 ulp in */1935+/* error in rare cases. */1936+/* ------------------------------------------------------------------ */1937+decNumber * decNumberPower(decNumber *res, const decNumber *lhs,1938+ const decNumber *rhs, decContext *set) {1939+ #if DECSUBSET1940+ decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated1941+ decNumber *allocrhs=NULL; // .., rhs1942+ #endif1943+ decNumber *allocdac=NULL; // -> allocated acc buffer, iff used1944+ decNumber *allocinv=NULL; // -> allocated 1/x buffer, iff used1945+ Int reqdigits=set->digits; // requested DIGITS1946+ Int n; // rhs in binary1947+ Flag rhsint=0; // 1 if rhs is an integer1948+ Flag useint=0; // 1 if can use integer calculation1949+ Flag isoddint=0; // 1 if rhs is an integer and odd1950+ Int i; // work1951+ #if DECSUBSET1952+ Int dropped; // ..1953+ #endif1954+ uInt needbytes; // buffer size needed1955+ Flag seenbit; // seen a bit while powering1956+ Int residue=0; // rounding residue1957+ uInt status=0; // accumulators1958+ uByte bits=0; // result sign if errors1959+ decContext aset; // working context1960+ decNumber dnOne; // work value 1...1961+ // local accumulator buffer [a decNumber, with digits+elength+1 digits]1962+ decNumber dacbuff[D2N(DECBUFFER+9)];1963+ decNumber *dac=dacbuff; // -> result accumulator1964+ // same again for possible 1/lhs calculation1965+ decNumber invbuff[D2N(DECBUFFER+9)];1966+1967+ #if DECCHECK1968+ if (decCheckOperands(res, lhs, rhs, set)) return res;1969+ #endif1970+1971+ do { // protect allocated storage1972+ #if DECSUBSET1973+ if (!set->extended) { // reduce operands and set status, as needed1974+ if (lhs->digits>reqdigits) {1975+ alloclhs=decRoundOperand(lhs, set, &status);1976+ if (alloclhs==NULL) break;1977+ lhs=alloclhs;1978+ }1979+ if (rhs->digits>reqdigits) {1980+ allocrhs=decRoundOperand(rhs, set, &status);1981+ if (allocrhs==NULL) break;1982+ rhs=allocrhs;1983+ }1984+ }1985+ #endif1986+ // [following code does not require input rounding]1987+1988+ // handle NaNs and rhs Infinity (lhs infinity is harder)1989+ if (SPECIALARGS) {1990+ if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs1991+ decNaNs(res, lhs, rhs, set, &status);1992+ break;}1993+ if (decNumberIsInfinite(rhs)) { // rhs Infinity1994+ Flag rhsneg=rhs->bits&DECNEG; // save rhs sign1995+ if (decNumberIsNegative(lhs) // lhs<01996+ && !decNumberIsZero(lhs)) // ..1997+ status|=DEC_Invalid_operation;1998+ else { // lhs >=01999+ decNumberZero(&dnOne); // set up 12000+ dnOne.lsu[0]=1;2001+ decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 12002+ decNumberZero(res); // prepare for 0/1/Infinity2003+ if (decNumberIsNegative(dac)) { // lhs<12004+ if (rhsneg) res->bits|=DECINF; // +Infinity [else is +0]2005+ }2006+ else if (dac->lsu[0]==0) { // lhs=12007+ // 1**Infinity is inexact, so return fully-padded 1.00002008+ Int shift=set->digits-1;2009+ *res->lsu=1; // was 0, make int 12010+ res->digits=decShiftToMost(res->lsu, 1, shift);2011+ res->exponent=-shift; // make 1.0000...2012+ status|=DEC_Inexact|DEC_Rounded; // deemed inexact2013+ }2014+ else { // lhs>12015+ if (!rhsneg) res->bits|=DECINF; // +Infinity [else is +0]2016+ }2017+ } // lhs>=02018+ break;}2019+ // [lhs infinity drops through]2020+ } // specials2021+2022+ // Original rhs may be an integer that fits and is in range2023+ n=decGetInt(rhs);2024+ if (n!=BADINT) { // it is an integer2025+ rhsint=1; // record the fact for 1**n2026+ isoddint=(Flag)n&1; // [works even if big]2027+ if (n!=BIGEVEN && n!=BIGODD) // can use integer path?2028+ useint=1; // looks good2029+ }2030+2031+ if (decNumberIsNegative(lhs) // -x ..2032+ && isoddint) bits=DECNEG; // .. to an odd power2033+2034+ // handle LHS infinity2035+ if (decNumberIsInfinite(lhs)) { // [NaNs already handled]2036+ uByte rbits=rhs->bits; // save2037+ decNumberZero(res); // prepare2038+ if (n==0) *res->lsu=1; // [-]Inf**0 => 12039+ else {2040+ // -Inf**nonint -> error2041+ if (!rhsint && decNumberIsNegative(lhs)) {2042+ status|=DEC_Invalid_operation; // -Inf**nonint is error2043+ break;}2044+ if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n2045+ // [otherwise will be 0 or -0]2046+ res->bits=bits;2047+ }2048+ break;}2049+2050+ // similarly handle LHS zero2051+ if (decNumberIsZero(lhs)) {2052+ if (n==0) { // 0**0 => Error2053+ #if DECSUBSET2054+ if (!set->extended) { // [unless subset]2055+ decNumberZero(res);2056+ *res->lsu=1; // return 12057+ break;}2058+ #endif2059+ status|=DEC_Invalid_operation;2060+ }2061+ else { // 0**x2062+ uByte rbits=rhs->bits; // save2063+ if (rbits & DECNEG) { // was a 0**(-n)2064+ #if DECSUBSET2065+ if (!set->extended) { // [bad if subset]2066+ status|=DEC_Invalid_operation;2067+ break;}2068+ #endif2069+ bits|=DECINF;2070+ }2071+ decNumberZero(res); // prepare2072+ // [otherwise will be 0 or -0]2073+ res->bits=bits;2074+ }2075+ break;}2076+2077+ // here both lhs and rhs are finite; rhs==0 is handled in the2078+ // integer path. Next handle the non-integer cases2079+ if (!useint) { // non-integral rhs2080+ // any -ve lhs is bad, as is either operand or context out of2081+ // bounds2082+ if (decNumberIsNegative(lhs)) {2083+ status|=DEC_Invalid_operation;2084+ break;}2085+ if (decCheckMath(lhs, set, &status)2086+ || decCheckMath(rhs, set, &status)) break; // variable status2087+2088+ decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context2089+ aset.emax=DEC_MAX_MATH; // usual bounds2090+ aset.emin=-DEC_MAX_MATH; // ..2091+ aset.clamp=0; // and no concrete format2092+2093+ // calculate the result using exp(ln(lhs)*rhs), which can2094+ // all be done into the accumulator, dac. The precision needed2095+ // is enough to contain the full information in the lhs (which2096+ // is the total digits, including exponent), or the requested2097+ // precision, if larger, + 4; 6 is used for the exponent2098+ // maximum length, and this is also used when it is shorter2099+ // than the requested digits as it greatly reduces the >0.5 ulp2100+ // cases at little cost (because Ln doubles digits each2101+ // iteration so a few extra digits rarely causes an extra2102+ // iteration)2103+ aset.digits=MAXI(lhs->digits, set->digits)+6+4;2104+ } // non-integer rhs2105+2106+ else { // rhs is in-range integer2107+ if (n==0) { // x**0 = 12108+ // (0**0 was handled above)2109+ decNumberZero(res); // result=12110+ *res->lsu=1; // ..2111+ break;}2112+ // rhs is a non-zero integer2113+ if (n<0) n=-n; // use abs(n)2114+2115+ aset=*set; // clone the context2116+ aset.round=DEC_ROUND_HALF_EVEN; // internally use balanced2117+ // calculate the working DIGITS2118+ aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;2119+ #if DECSUBSET2120+ if (!set->extended) aset.digits--; // use classic precision2121+ #endif2122+ // it's an error if this is more than can be handled2123+ if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}2124+ } // integer path2125+2126+ // aset.digits is the count of digits for the accumulator needed2127+ // if accumulator is too long for local storage, then allocate2128+ needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);2129+ // [needbytes also used below if 1/lhs needed]2130+ if (needbytes>sizeof(dacbuff)) {2131+ allocdac=(decNumber *)malloc(needbytes);2132+ if (allocdac==NULL) { // hopeless -- abandon2133+ status|=DEC_Insufficient_storage;2134+ break;}2135+ dac=allocdac; // use the allocated space2136+ }2137+ // here, aset is set up and accumulator is ready for use2138+2139+ if (!useint) { // non-integral rhs2140+ // x ** y; special-case x=1 here as it will otherwise always2141+ // reduce to integer 1; decLnOp has a fastpath which detects2142+ // the case of x=12143+ decLnOp(dac, lhs, &aset, &status); // dac=ln(lhs)2144+ // [no error possible, as lhs 0 already handled]2145+ if (ISZERO(dac)) { // x==1, 1.0, etc.2146+ // need to return fully-padded 1.0000 etc., but rhsint->12147+ *dac->lsu=1; // was 0, make int 12148+ if (!rhsint) { // add padding2149+ Int shift=set->digits-1;2150+ dac->digits=decShiftToMost(dac->lsu, 1, shift);2151+ dac->exponent=-shift; // make 1.0000...2152+ status|=DEC_Inexact|DEC_Rounded; // deemed inexact2153+ }2154+ }2155+ else {2156+ decMultiplyOp(dac, dac, rhs, &aset, &status); // dac=dac*rhs2157+ decExpOp(dac, dac, &aset, &status); // dac=exp(dac)2158+ }2159+ // and drop through for final rounding2160+ } // non-integer rhs2161+2162+ else { // carry on with integer2163+ decNumberZero(dac); // acc=12164+ *dac->lsu=1; // ..2165+2166+ // if a negative power the constant 1 is needed, and if not subset2167+ // invert the lhs now rather than inverting the result later2168+ if (decNumberIsNegative(rhs)) { // was a **-n [hence digits>0]2169+ decNumber *inv=invbuff; // asssume use fixed buffer2170+ decNumberCopy(&dnOne, dac); // dnOne=1; [needed now or later]2171+ #if DECSUBSET2172+ if (set->extended) { // need to calculate 1/lhs2173+ #endif2174+ // divide lhs into 1, putting result in dac [dac=1/dac]2175+ decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);2176+ // now locate or allocate space for the inverted lhs2177+ if (needbytes>sizeof(invbuff)) {2178+ allocinv=(decNumber *)malloc(needbytes);2179+ if (allocinv==NULL) { // hopeless -- abandon2180+ status|=DEC_Insufficient_storage;2181+ break;}2182+ inv=allocinv; // use the allocated space2183+ }2184+ // [inv now points to big-enough buffer or allocated storage]2185+ decNumberCopy(inv, dac); // copy the 1/lhs2186+ decNumberCopy(dac, &dnOne); // restore acc=12187+ lhs=inv; // .. and go forward with new lhs2188+ #if DECSUBSET2189+ }2190+ #endif2191+ }2192+2193+ // Raise-to-the-power loop...2194+ seenbit=0; // set once a 1-bit is encountered2195+ for (i=1;;i++){ // for each bit [top bit ignored]2196+ // abandon if had overflow or terminal underflow2197+ if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?2198+ if (status&DEC_Overflow || ISZERO(dac)) break;2199+ }2200+ // [the following two lines revealed an optimizer bug in a C++2201+ // compiler, with symptom: 5**3 -> 25, when n=n+n was used]2202+ n=n<<1; // move next bit to testable position2203+ if (n<0) { // top bit is set2204+ seenbit=1; // OK, significant bit seen2205+ decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x2206+ }2207+ if (i==31) break; // that was the last bit2208+ if (!seenbit) continue; // no need to square 12209+ decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]2210+ } /*i*/ // 32 bits2211+2212+ // complete internal overflow or underflow processing2213+ if (status & (DEC_Overflow|DEC_Underflow)) {2214+ #if DECSUBSET2215+ // If subset, and power was negative, reverse the kind of -erflow2216+ // [1/x not yet done]2217+ if (!set->extended && decNumberIsNegative(rhs)) {2218+ if (status & DEC_Overflow)2219+ status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;2220+ else { // trickier -- Underflow may or may not be set2221+ status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]2222+ status|=DEC_Overflow;2223+ }2224+ }2225+ #endif2226+ dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign2227+ // round subnormals [to set.digits rather than aset.digits]2228+ // or set overflow result similarly as required2229+ decFinalize(dac, set, &residue, &status);2230+ decNumberCopy(res, dac); // copy to result (is now OK length)2231+ break;2232+ }2233+2234+ #if DECSUBSET2235+ if (!set->extended && // subset math2236+ decNumberIsNegative(rhs)) { // was a **-n [hence digits>0]2237+ // so divide result into 1 [dac=1/dac]2238+ decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);2239+ }2240+ #endif2241+ } // rhs integer path2242+2243+ // reduce result to the requested length and copy to result2244+ decCopyFit(res, dac, set, &residue, &status);2245+ decFinish(res, set, &residue, &status); // final cleanup2246+ #if DECSUBSET2247+ if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros2248+ #endif2249+ } while(0); // end protected2250+2251+ if (allocdac!=NULL) free(allocdac); // drop any storage used2252+ if (allocinv!=NULL) free(allocinv); // ..2253+ #if DECSUBSET2254+ if (alloclhs!=NULL) free(alloclhs); // ..2255+ if (allocrhs!=NULL) free(allocrhs); // ..2256+ #endif2257+ if (status!=0) decStatus(res, status, set);2258+ #if DECCHECK2259+ decCheckInexact(res, set);2260+ #endif2261+ return res;2262+ } // decNumberPower2263+2264+/* ------------------------------------------------------------------ */2265+/* decNumberQuantize -- force exponent to requested value */2266+/* */2267+/* This computes C = op(A, B), where op adjusts the coefficient */2268+/* of C (by rounding or shifting) such that the exponent (-scale) */2269+/* of C has exponent of B. The numerical value of C will equal A, */2270+/* except for the effects of any rounding that occurred. */2271+/* */2272+/* res is C, the result. C may be A or B */2273+/* lhs is A, the number to adjust */2274+/* rhs is B, the number with exponent to match */2275+/* set is the context */2276+/* */2277+/* C must have space for set->digits digits. */2278+/* */2279+/* Unless there is an error or the result is infinite, the exponent */2280+/* after the operation is guaranteed to be equal to that of B. */2281+/* ------------------------------------------------------------------ */2282+decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,2283+ const decNumber *rhs, decContext *set) {2284+ uInt status=0; // accumulator2285+ decQuantizeOp(res, lhs, rhs, set, 1, &status);2286+ if (status!=0) decStatus(res, status, set);2287+ return res;2288+ } // decNumberQuantize2289+2290+/* ------------------------------------------------------------------ */2291+/* decNumberReduce -- remove trailing zeros */2292+/* */2293+/* This computes C = 0 + A, and normalizes the result */2294+/* */2295+/* res is C, the result. C may be A */2296+/* rhs is A */2297+/* set is the context */2298+/* */2299+/* C must have space for set->digits digits. */2300+/* ------------------------------------------------------------------ */2301+// Previously known as Normalize2302+decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,2303+ decContext *set) {2304+ return decNumberReduce(res, rhs, set);2305+ } // decNumberNormalize2306+2307+decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,2308+ decContext *set) {2309+ #if DECSUBSET2310+ decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated2311+ #endif2312+ uInt status=0; // as usual2313+ Int residue=0; // as usual2314+ Int dropped; // work2315+2316+ #if DECCHECK2317+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;2318+ #endif2319+2320+ do { // protect allocated storage2321+ #if DECSUBSET2322+ if (!set->extended) {2323+ // reduce operand and set lostDigits status, as needed2324+ if (rhs->digits>set->digits) {2325+ allocrhs=decRoundOperand(rhs, set, &status);2326+ if (allocrhs==NULL) break;2327+ rhs=allocrhs;2328+ }2329+ }2330+ #endif2331+ // [following code does not require input rounding]2332+2333+ // Infinities copy through; NaNs need usual treatment2334+ if (decNumberIsNaN(rhs)) {2335+ decNaNs(res, rhs, NULL, set, &status);2336+ break;2337+ }2338+2339+ // reduce result to the requested length and copy to result2340+ decCopyFit(res, rhs, set, &residue, &status); // copy & round2341+ decFinish(res, set, &residue, &status); // cleanup/set flags2342+ decTrim(res, set, 1, 0, &dropped); // normalize in place2343+ // [may clamp]2344+ } while(0); // end protected2345+2346+ #if DECSUBSET2347+ if (allocrhs !=NULL) free(allocrhs); // ..2348+ #endif2349+ if (status!=0) decStatus(res, status, set);// then report status2350+ return res;2351+ } // decNumberReduce2352+2353+/* ------------------------------------------------------------------ */2354+/* decNumberRescale -- force exponent to requested value */2355+/* */2356+/* This computes C = op(A, B), where op adjusts the coefficient */2357+/* of C (by rounding or shifting) such that the exponent (-scale) */2358+/* of C has the value B. The numerical value of C will equal A, */2359+/* except for the effects of any rounding that occurred. */2360+/* */2361+/* res is C, the result. C may be A or B */2362+/* lhs is A, the number to adjust */2363+/* rhs is B, the requested exponent */2364+/* set is the context */2365+/* */2366+/* C must have space for set->digits digits. */2367+/* */2368+/* Unless there is an error or the result is infinite, the exponent */2369+/* after the operation is guaranteed to be equal to B. */2370+/* ------------------------------------------------------------------ */2371+decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,2372+ const decNumber *rhs, decContext *set) {2373+ uInt status=0; // accumulator2374+ decQuantizeOp(res, lhs, rhs, set, 0, &status);2375+ if (status!=0) decStatus(res, status, set);2376+ return res;2377+ } // decNumberRescale2378+2379+/* ------------------------------------------------------------------ */2380+/* decNumberRemainder -- divide and return remainder */2381+/* */2382+/* This computes C = A % B */2383+/* */2384+/* res is C, the result. C may be A and/or B (e.g., X=X%X) */2385+/* lhs is A */2386+/* rhs is B */2387+/* set is the context */2388+/* */2389+/* C must have space for set->digits digits. */2390+/* ------------------------------------------------------------------ */2391+decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,2392+ const decNumber *rhs, decContext *set) {2393+ uInt status=0; // accumulator2394+ decDivideOp(res, lhs, rhs, set, REMAINDER, &status);2395+ if (status!=0) decStatus(res, status, set);2396+ #if DECCHECK2397+ decCheckInexact(res, set);2398+ #endif2399+ return res;2400+ } // decNumberRemainder2401+2402+/* ------------------------------------------------------------------ */2403+/* decNumberRemainderNear -- divide and return remainder from nearest */2404+/* */2405+/* This computes C = A % B, where % is the IEEE remainder operator */2406+/* */2407+/* res is C, the result. C may be A and/or B (e.g., X=X%X) */2408+/* lhs is A */2409+/* rhs is B */2410+/* set is the context */2411+/* */2412+/* C must have space for set->digits digits. */2413+/* ------------------------------------------------------------------ */2414+decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,2415+ const decNumber *rhs, decContext *set) {2416+ uInt status=0; // accumulator2417+ decDivideOp(res, lhs, rhs, set, REMNEAR, &status);2418+ if (status!=0) decStatus(res, status, set);2419+ #if DECCHECK2420+ decCheckInexact(res, set);2421+ #endif2422+ return res;2423+ } // decNumberRemainderNear2424+2425+/* ------------------------------------------------------------------ */2426+/* decNumberRotate -- rotate the coefficient of a Number left/right */2427+/* */2428+/* This computes C = A rot B (in base ten and rotating set->digits */2429+/* digits). */2430+/* */2431+/* res is C, the result. C may be A and/or B (e.g., X=XrotX) */2432+/* lhs is A */2433+/* rhs is B, the number of digits to rotate (-ve to right) */2434+/* set is the context */2435+/* */2436+/* The digits of the coefficient of A are rotated to the left (if B */2437+/* is positive) or to the right (if B is negative) without adjusting */2438+/* the exponent or the sign of A. If lhs->digits is less than */2439+/* set->digits the coefficient is padded with zeros on the left */2440+/* before the rotate. Any leading zeros in the result are removed */2441+/* as usual. */2442+/* */2443+/* B must be an integer (q=0) and in the range -set->digits through */2444+/* +set->digits. */2445+/* C must have space for set->digits digits. */2446+/* NaNs are propagated as usual. Infinities are unaffected (but */2447+/* B must be valid). No status is set unless B is invalid or an */2448+/* operand is an sNaN. */2449+/* ------------------------------------------------------------------ */2450+decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,2451+ const decNumber *rhs, decContext *set) {2452+ uInt status=0; // accumulator2453+ Int rotate; // rhs as an Int2454+2455+ #if DECCHECK2456+ if (decCheckOperands(res, lhs, rhs, set)) return res;2457+ #endif2458+2459+ // NaNs propagate as normal2460+ if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))2461+ decNaNs(res, lhs, rhs, set, &status);2462+ // rhs must be an integer2463+ else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)2464+ status=DEC_Invalid_operation;2465+ else { // both numeric, rhs is an integer2466+ rotate=decGetInt(rhs); // [cannot fail]2467+ if (rotate==BADINT // something bad ..2468+ || rotate==BIGODD || rotate==BIGEVEN // .. very big ..2469+ || abs(rotate)>set->digits) // .. or out of range2470+ status=DEC_Invalid_operation;2471+ else { // rhs is OK2472+ decNumberCopy(res, lhs);2473+ // convert -ve rotate to equivalent positive rotation2474+ if (rotate<0) rotate=set->digits+rotate;2475+ if (rotate!=0 && rotate!=set->digits // zero or full rotation2476+ && !decNumberIsInfinite(res)) { // lhs was infinite2477+ // left-rotate to do; 0 < rotate < set->digits2478+ uInt units, shift; // work2479+ uInt msudigits; // digits in result msu2480+ Unit *msu=res->lsu+D2U(res->digits)-1; // current msu2481+ Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu2482+ for (msu++; msu<=msumax; msu++) *msu=0; // ensure high units=02483+ res->digits=set->digits; // now full-length2484+ msudigits=MSUDIGITS(res->digits); // actual digits in msu2485+2486+ // rotation here is done in-place, in three steps2487+ // 1. shift all to least up to one unit to unit-align final2488+ // lsd [any digits shifted out are rotated to the left,2489+ // abutted to the original msd (which may require split)]2490+ //2491+ // [if there are no whole units left to rotate, the2492+ // rotation is now complete]2493+ //2494+ // 2. shift to least, from below the split point only, so that2495+ // the final msd is in the right place in its Unit [any2496+ // digits shifted out will fit exactly in the current msu,2497+ // left aligned, no split required]2498+ //2499+ // 3. rotate all the units by reversing left part, right2500+ // part, and then whole2501+ //2502+ // example: rotate right 8 digits (2 units + 2), DECDPUN=3.2503+ //2504+ // start: 00a bcd efg hij klm npq2505+ //2506+ // 1a 000 0ab cde fgh|ijk lmn [pq saved]2507+ // 1b 00p qab cde fgh|ijk lmn2508+ //2509+ // 2a 00p qab cde fgh|00i jkl [mn saved]2510+ // 2b mnp qab cde fgh|00i jkl2511+ //2512+ // 3a fgh cde qab mnp|00i jkl2513+ // 3b fgh cde qab mnp|jkl 00i2514+ // 3c 00i jkl mnp qab cde fgh2515+2516+ // Step 1: amount to shift is the partial right-rotate count2517+ rotate=set->digits-rotate; // make it right-rotate2518+ units=rotate/DECDPUN; // whole units to rotate2519+ shift=rotate%DECDPUN; // left-over digits count2520+ if (shift>0) { // not an exact number of units2521+ uInt save=res->lsu[0]%powers[shift]; // save low digit(s)2522+ decShiftToLeast(res->lsu, D2U(res->digits), shift);2523+ if (shift>msudigits) { // msumax-1 needs >0 digits2524+ uInt rem=save%powers[shift-msudigits];// split save2525+ *msumax=(Unit)(save/powers[shift-msudigits]); // and insert2526+ *(msumax-1)=*(msumax-1)2527+ +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..2528+ }2529+ else { // all fits in msumax2530+ *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]2531+ }2532+ } // digits shift needed2533+2534+ // If whole units to rotate...2535+ if (units>0) { // some to do2536+ // Step 2: the units to touch are the whole ones in rotate,2537+ // if any, and the shift is DECDPUN-msudigits (which may be2538+ // 0, again)2539+ shift=DECDPUN-msudigits;2540+ if (shift>0) { // not an exact number of units2541+ uInt save=res->lsu[0]%powers[shift]; // save low digit(s)2542+ decShiftToLeast(res->lsu, units, shift);2543+ *msumax=*msumax+(Unit)(save*powers[msudigits]);2544+ } // partial shift needed2545+2546+ // Step 3: rotate the units array using triple reverse2547+ // (reversing is easy and fast)2548+ decReverse(res->lsu+units, msumax); // left part2549+ decReverse(res->lsu, res->lsu+units-1); // right part2550+ decReverse(res->lsu, msumax); // whole2551+ } // whole units to rotate2552+ // the rotation may have left an undetermined number of zeros2553+ // on the left, so true length needs to be calculated2554+ res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);2555+ } // rotate needed2556+ } // rhs OK2557+ } // numerics2558+ if (status!=0) decStatus(res, status, set);2559+ return res;2560+ } // decNumberRotate2561+2562+/* ------------------------------------------------------------------ */2563+/* decNumberSameQuantum -- test for equal exponents */2564+/* */2565+/* res is the result number, which will contain either 0 or 1 */2566+/* lhs is a number to test */2567+/* rhs is the second (usually a pattern) */2568+/* */2569+/* No errors are possible and no context is needed. */2570+/* ------------------------------------------------------------------ */2571+decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,2572+ const decNumber *rhs) {2573+ Unit ret=0; // return value2574+2575+ #if DECCHECK2576+ if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;2577+ #endif2578+2579+ if (SPECIALARGS) {2580+ if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;2581+ else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;2582+ // [anything else with a special gives 0]2583+ }2584+ else if (lhs->exponent==rhs->exponent) ret=1;2585+2586+ decNumberZero(res); // OK to overwrite an operand now2587+ *res->lsu=ret;2588+ return res;2589+ } // decNumberSameQuantum2590+2591+/* ------------------------------------------------------------------ */2592+/* decNumberScaleB -- multiply by a power of 10 */2593+/* */2594+/* This computes C = A x 10**B where B is an integer (q=0) with */2595+/* maximum magnitude 2*(emax+digits) */2596+/* */2597+/* res is C, the result. C may be A or B */2598+/* lhs is A, the number to adjust */2599+/* rhs is B, the requested power of ten to use */2600+/* set is the context */2601+/* */2602+/* C must have space for set->digits digits. */2603+/* */2604+/* The result may underflow or overflow. */2605+/* ------------------------------------------------------------------ */2606+decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,2607+ const decNumber *rhs, decContext *set) {2608+ Int reqexp; // requested exponent change [B]2609+ uInt status=0; // accumulator2610+ Int residue; // work2611+2612+ #if DECCHECK2613+ if (decCheckOperands(res, lhs, rhs, set)) return res;2614+ #endif2615+2616+ // Handle special values except lhs infinite2617+ if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))2618+ decNaNs(res, lhs, rhs, set, &status);2619+ // rhs must be an integer2620+ else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)2621+ status=DEC_Invalid_operation;2622+ else {2623+ // lhs is a number; rhs is a finite with q==02624+ reqexp=decGetInt(rhs); // [cannot fail]2625+ // maximum range is larger than getInt can handle, so this is2626+ // more restrictive than the specification2627+ if (reqexp==BADINT // something bad ..2628+ || reqexp==BIGODD || reqexp==BIGEVEN // it was huge2629+ || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range2630+ status=DEC_Invalid_operation;2631+ else { // rhs is OK2632+ decNumberCopy(res, lhs); // all done if infinite lhs2633+ if (!decNumberIsInfinite(res)) { // prepare to scale2634+ Int exp=res->exponent; // save for overflow test2635+ res->exponent+=reqexp; // adjust the exponent2636+ if (((exp^reqexp)>=0) // same sign ...2637+ && ((exp^res->exponent)<0)) { // .. but result had different2638+ // the calculation overflowed, so force right treatment2639+ if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;2640+ else res->exponent=DEC_MAX_EMAX+1;2641+ }2642+ residue=0;2643+ decFinalize(res, set, &residue, &status); // final check2644+ } // finite LHS2645+ } // rhs OK2646+ } // rhs finite2647+ if (status!=0) decStatus(res, status, set);2648+ return res;2649+ } // decNumberScaleB2650+2651+/* ------------------------------------------------------------------ */2652+/* decNumberShift -- shift the coefficient of a Number left or right */2653+/* */2654+/* This computes C = A << B or C = A >> -B (in base ten). */2655+/* */2656+/* res is C, the result. C may be A and/or B (e.g., X=X<<X) */2657+/* lhs is A */2658+/* rhs is B, the number of digits to shift (-ve to right) */2659+/* set is the context */2660+/* */2661+/* The digits of the coefficient of A are shifted to the left (if B */2662+/* is positive) or to the right (if B is negative) without adjusting */2663+/* the exponent or the sign of A. */2664+/* */2665+/* B must be an integer (q=0) and in the range -set->digits through */2666+/* +set->digits. */2667+/* C must have space for set->digits digits. */2668+/* NaNs are propagated as usual. Infinities are unaffected (but */2669+/* B must be valid). No status is set unless B is invalid or an */2670+/* operand is an sNaN. */2671+/* ------------------------------------------------------------------ */2672+decNumber * decNumberShift(decNumber *res, const decNumber *lhs,2673+ const decNumber *rhs, decContext *set) {2674+ uInt status=0; // accumulator2675+ Int shift; // rhs as an Int2676+2677+ #if DECCHECK2678+ if (decCheckOperands(res, lhs, rhs, set)) return res;2679+ #endif2680+2681+ // NaNs propagate as normal2682+ if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))2683+ decNaNs(res, lhs, rhs, set, &status);2684+ // rhs must be an integer2685+ else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)2686+ status=DEC_Invalid_operation;2687+ else { // both numeric, rhs is an integer2688+ shift=decGetInt(rhs); // [cannot fail]2689+ if (shift==BADINT // something bad ..2690+ || shift==BIGODD || shift==BIGEVEN // .. very big ..2691+ || abs(shift)>set->digits) // .. or out of range2692+ status=DEC_Invalid_operation;2693+ else { // rhs is OK2694+ decNumberCopy(res, lhs);2695+ if (shift!=0 && !decNumberIsInfinite(res)) { // something to do2696+ if (shift>0) { // to left2697+ if (shift==set->digits) { // removing all2698+ *res->lsu=0; // so place 02699+ res->digits=1; // ..2700+ }2701+ else { //2702+ // first remove leading digits if necessary2703+ if (res->digits+shift>set->digits) {2704+ decDecap(res, res->digits+shift-set->digits);2705+ // that updated res->digits; may have gone to 1 (for a2706+ // single digit or for zero2707+ }2708+ if (res->digits>1 || *res->lsu) // if non-zero..2709+ res->digits=decShiftToMost(res->lsu, res->digits, shift);2710+ } // partial left2711+ } // left2712+ else { // to right2713+ if (-shift>=res->digits) { // discarding all2714+ *res->lsu=0; // so place 02715+ res->digits=1; // ..2716+ }2717+ else {2718+ decShiftToLeast(res->lsu, D2U(res->digits), -shift);2719+ res->digits-=(-shift);2720+ }2721+ } // to right2722+ } // non-0 non-Inf shift2723+ } // rhs OK2724+ } // numerics2725+ if (status!=0) decStatus(res, status, set);2726+ return res;2727+ } // decNumberShift2728+2729+/* ------------------------------------------------------------------ */2730+/* decNumberSquareRoot -- square root operator */2731+/* */2732+/* This computes C = squareroot(A) */2733+/* */2734+/* res is C, the result. C may be A */2735+/* rhs is A */2736+/* set is the context; note that rounding mode has no effect */2737+/* */2738+/* C must have space for set->digits digits. */2739+/* ------------------------------------------------------------------ */2740+/* This uses the following varying-precision algorithm in: */2741+/* */2742+/* Properly Rounded Variable Precision Square Root, T. E. Hull and */2743+/* A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */2744+/* pp229-237, ACM, September 1985. */2745+/* */2746+/* The square-root is calculated using Newton's method, after which */2747+/* a check is made to ensure the result is correctly rounded. */2748+/* */2749+/* % [Reformatted original Numerical Turing source code follows.] */2750+/* function sqrt(x : real) : real */2751+/* % sqrt(x) returns the properly rounded approximation to the square */2752+/* % root of x, in the precision of the calling environment, or it */2753+/* % fails if x < 0. */2754+/* % t e hull and a abrham, august, 1984 */2755+/* if x <= 0 then */2756+/* if x < 0 then */2757+/* assert false */2758+/* else */2759+/* result 0 */2760+/* end if */2761+/* end if */2762+/* var f := setexp(x, 0) % fraction part of x [0.1 <= x < 1] */2763+/* var e := getexp(x) % exponent part of x */2764+/* var approx : real */2765+/* if e mod 2 = 0 then */2766+/* approx := .259 + .819 * f % approx to root of f */2767+/* else */2768+/* f := f/l0 % adjustments */2769+/* e := e + 1 % for odd */2770+/* approx := .0819 + 2.59 * f % exponent */2771+/* end if */2772+/* */2773+/* var p:= 3 */2774+/* const maxp := currentprecision + 2 */2775+/* loop */2776+/* p := min(2*p - 2, maxp) % p = 4,6,10, . . . , maxp */2777+/* precision p */2778+/* approx := .5 * (approx + f/approx) */2779+/* exit when p = maxp */2780+/* end loop */2781+/* */2782+/* % approx is now within 1 ulp of the properly rounded square root */2783+/* % of f; to ensure proper rounding, compare squares of (approx - */2784+/* % l/2 ulp) and (approx + l/2 ulp) with f. */2785+/* p := currentprecision */2786+/* begin */2787+/* precision p + 2 */2788+/* const approxsubhalf := approx - setexp(.5, -p) */2789+/* if mulru(approxsubhalf, approxsubhalf) > f then */2790+/* approx := approx - setexp(.l, -p + 1) */2791+/* else */2792+/* const approxaddhalf := approx + setexp(.5, -p) */2793+/* if mulrd(approxaddhalf, approxaddhalf) < f then */2794+/* approx := approx + setexp(.l, -p + 1) */2795+/* end if */2796+/* end if */2797+/* end */2798+/* result setexp(approx, e div 2) % fix exponent */2799+/* end sqrt */2800+/* ------------------------------------------------------------------ */2801+decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,2802+ decContext *set) {2803+ decContext workset, approxset; // work contexts2804+ decNumber dzero; // used for constant zero2805+ Int maxp; // largest working precision2806+ Int workp; // working precision2807+ Int residue=0; // rounding residue2808+ uInt status=0, ignore=0; // status accumulators2809+ uInt rstatus; // ..2810+ Int exp; // working exponent2811+ Int ideal; // ideal (preferred) exponent2812+ Int needbytes; // work2813+ Int dropped; // ..2814+2815+ #if DECSUBSET2816+ decNumber *allocrhs=NULL; // non-NULL if rounded rhs allocated2817+ #endif2818+ // buffer for f [needs +1 in case DECBUFFER 0]2819+ decNumber buff[D2N(DECBUFFER+1)];2820+ // buffer for a [needs +2 to match likely maxp]2821+ decNumber bufa[D2N(DECBUFFER+2)];2822+ // buffer for temporary, b [must be same size as a]2823+ decNumber bufb[D2N(DECBUFFER+2)];2824+ decNumber *allocbuff=NULL; // -> allocated buff, iff allocated2825+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated2826+ decNumber *allocbufb=NULL; // -> allocated bufb, iff allocated2827+ decNumber *f=buff; // reduced fraction2828+ decNumber *a=bufa; // approximation to result2829+ decNumber *b=bufb; // intermediate result2830+ // buffer for temporary variable, up to 3 digits2831+ decNumber buft[D2N(3)];2832+ decNumber *t=buft; // up-to-3-digit constant or work2833+2834+ #if DECCHECK2835+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;2836+ #endif2837+2838+ do { // protect allocated storage2839+ #if DECSUBSET2840+ if (!set->extended) {2841+ // reduce operand and set lostDigits status, as needed2842+ if (rhs->digits>set->digits) {2843+ allocrhs=decRoundOperand(rhs, set, &status);2844+ if (allocrhs==NULL) break;2845+ // [Note: 'f' allocation below could reuse this buffer if2846+ // used, but as this is rare they are kept separate for clarity.]2847+ rhs=allocrhs;2848+ }2849+ }2850+ #endif2851+ // [following code does not require input rounding]2852+2853+ // handle infinities and NaNs2854+ if (SPECIALARG) {2855+ if (decNumberIsInfinite(rhs)) { // an infinity2856+ if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;2857+ else decNumberCopy(res, rhs); // +Infinity2858+ }2859+ else decNaNs(res, rhs, NULL, set, &status); // a NaN2860+ break;2861+ }2862+2863+ // calculate the ideal (preferred) exponent [floor(exp/2)]2864+ // [It would be nicer to write: ideal=rhs->exponent>>1, but this2865+ // generates a compiler warning. Generated code is the same.]2866+ ideal=(rhs->exponent&~1)/2; // target2867+2868+ // handle zeros2869+ if (ISZERO(rhs)) {2870+ decNumberCopy(res, rhs); // could be 0 or -02871+ res->exponent=ideal; // use the ideal [safe]2872+ // use decFinish to clamp any out-of-range exponent, etc.2873+ decFinish(res, set, &residue, &status);2874+ break;2875+ }2876+2877+ // any other -x is an oops2878+ if (decNumberIsNegative(rhs)) {2879+ status|=DEC_Invalid_operation;2880+ break;2881+ }2882+2883+ // space is needed for three working variables2884+ // f -- the same precision as the RHS, reduced to 0.01->0.99...2885+ // a -- Hull's approximation -- precision, when assigned, is2886+ // currentprecision+1 or the input argument precision,2887+ // whichever is larger (+2 for use as temporary)2888+ // b -- intermediate temporary result (same size as a)2889+ // if any is too long for local storage, then allocate2890+ workp=MAXI(set->digits+1, rhs->digits); // actual rounding precision2891+ workp=MAXI(workp, 7); // at least 7 for low cases2892+ maxp=workp+2; // largest working precision2893+2894+ needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);2895+ if (needbytes>(Int)sizeof(buff)) {2896+ allocbuff=(decNumber *)malloc(needbytes);2897+ if (allocbuff==NULL) { // hopeless -- abandon2898+ status|=DEC_Insufficient_storage;2899+ break;}2900+ f=allocbuff; // use the allocated space2901+ }2902+ // a and b both need to be able to hold a maxp-length number2903+ needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);2904+ if (needbytes>(Int)sizeof(bufa)) { // [same applies to b]2905+ allocbufa=(decNumber *)malloc(needbytes);2906+ allocbufb=(decNumber *)malloc(needbytes);2907+ if (allocbufa==NULL || allocbufb==NULL) { // hopeless2908+ status|=DEC_Insufficient_storage;2909+ break;}2910+ a=allocbufa; // use the allocated spaces2911+ b=allocbufb; // ..2912+ }2913+2914+ // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 12915+ decNumberCopy(f, rhs);2916+ exp=f->exponent+f->digits; // adjusted to Hull rules2917+ f->exponent=-(f->digits); // to range2918+2919+ // set up working context2920+ decContextDefault(&workset, DEC_INIT_DECIMAL64);2921+ workset.emax=DEC_MAX_EMAX;2922+ workset.emin=DEC_MIN_EMIN;2923+2924+ // [Until further notice, no error is possible and status bits2925+ // (Rounded, etc.) should be ignored, not accumulated.]2926+2927+ // Calculate initial approximation, and allow for odd exponent2928+ workset.digits=workp; // p for initial calculation2929+ t->bits=0; t->digits=3;2930+ a->bits=0; a->digits=3;2931+ if ((exp & 1)==0) { // even exponent2932+ // Set t=0.259, a=0.8192933+ t->exponent=-3;2934+ a->exponent=-3;2935+ #if DECDPUN>=32936+ t->lsu[0]=259;2937+ a->lsu[0]=819;2938+ #elif DECDPUN==22939+ t->lsu[0]=59; t->lsu[1]=2;2940+ a->lsu[0]=19; a->lsu[1]=8;2941+ #else2942+ t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;2943+ a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;2944+ #endif2945+ }2946+ else { // odd exponent2947+ // Set t=0.0819, a=2.592948+ f->exponent--; // f=f/102949+ exp++; // e=e+12950+ t->exponent=-4;2951+ a->exponent=-2;2952+ #if DECDPUN>=32953+ t->lsu[0]=819;2954+ a->lsu[0]=259;2955+ #elif DECDPUN==22956+ t->lsu[0]=19; t->lsu[1]=8;2957+ a->lsu[0]=59; a->lsu[1]=2;2958+ #else2959+ t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;2960+ a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;2961+ #endif2962+ }2963+2964+ decMultiplyOp(a, a, f, &workset, &ignore); // a=a*f2965+ decAddOp(a, a, t, &workset, 0, &ignore); // ..+t2966+ // [a is now the initial approximation for sqrt(f), calculated with2967+ // currentprecision, which is also a's precision.]2968+2969+ // the main calculation loop2970+ decNumberZero(&dzero); // make 02971+ decNumberZero(t); // set t = 0.52972+ t->lsu[0]=5; // ..2973+ t->exponent=-1; // ..2974+ workset.digits=3; // initial p2975+ for (; workset.digits<maxp;) {2976+ // set p to min(2*p - 2, maxp) [hence 3; or: 4, 6, 10, ... , maxp]2977+ workset.digits=MINI(workset.digits*2-2, maxp);2978+ // a = 0.5 * (a + f/a)2979+ // [calculated at p then rounded to currentprecision]2980+ decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a2981+ decAddOp(b, b, a, &workset, 0, &ignore); // b=b+a2982+ decMultiplyOp(a, b, t, &workset, &ignore); // a=b*0.52983+ } // loop2984+2985+ // Here, 0.1 <= a < 1 [Hull], and a has maxp digits2986+ // now reduce to length, etc.; this needs to be done with a2987+ // having the correct exponent so as to handle subnormals2988+ // correctly2989+ approxset=*set; // get emin, emax, etc.2990+ approxset.round=DEC_ROUND_HALF_EVEN;2991+ a->exponent+=exp/2; // set correct exponent2992+ rstatus=0; // clear status2993+ residue=0; // .. and accumulator2994+ decCopyFit(a, a, &approxset, &residue, &rstatus); // reduce (if needed)2995+ decFinish(a, &approxset, &residue, &rstatus); // clean and finalize2996+2997+ // Overflow was possible if the input exponent was out-of-range,2998+ // in which case quit2999+ if (rstatus&DEC_Overflow) {3000+ status=rstatus; // use the status as-is3001+ decNumberCopy(res, a); // copy to result3002+ break;3003+ }3004+3005+ // Preserve status except Inexact/Rounded3006+ status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));3007+3008+ // Carry out the Hull correction3009+ a->exponent-=exp/2; // back to 0.1->13010+3011+ // a is now at final precision and within 1 ulp of the properly3012+ // rounded square root of f; to ensure proper rounding, compare3013+ // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.3014+ // Here workset.digits=maxp and t=0.5, and a->digits determines3015+ // the ulp3016+ workset.digits--; // maxp-1 is OK now3017+ t->exponent=-a->digits-1; // make 0.5 ulp3018+ decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp3019+ workset.round=DEC_ROUND_UP;3020+ decMultiplyOp(b, b, b, &workset, &ignore); // b = mulru(b, b)3021+ decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed3022+ if (decNumberIsNegative(b)) { // f < b [i.e., b > f]3023+ // this is the more common adjustment, though both are rare3024+ t->exponent++; // make 1.0 ulp3025+ t->lsu[0]=1; // ..3026+ decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp3027+ // assign to approx [round to length]3028+ approxset.emin-=exp/2; // adjust to match a3029+ approxset.emax-=exp/2;3030+ decAddOp(a, &dzero, a, &approxset, 0, &ignore);3031+ }3032+ else {3033+ decAddOp(b, a, t, &workset, 0, &ignore); // b = a + 0.5 ulp3034+ workset.round=DEC_ROUND_DOWN;3035+ decMultiplyOp(b, b, b, &workset, &ignore); // b = mulrd(b, b)3036+ decCompareOp(b, b, f, &workset, COMPARE, &ignore); // b ? f3037+ if (decNumberIsNegative(b)) { // b < f3038+ t->exponent++; // make 1.0 ulp3039+ t->lsu[0]=1; // ..3040+ decAddOp(a, a, t, &workset, 0, &ignore); // a = a + 1 ulp3041+ // assign to approx [round to length]3042+ approxset.emin-=exp/2; // adjust to match a3043+ approxset.emax-=exp/2;3044+ decAddOp(a, &dzero, a, &approxset, 0, &ignore);3045+ }3046+ }3047+ // [no errors are possible in the above, and rounding/inexact during3048+ // estimation are irrelevant, so status was not accumulated]3049+3050+ // Here, 0.1 <= a < 1 (still), so adjust back3051+ a->exponent+=exp/2; // set correct exponent3052+3053+ // count droppable zeros [after any subnormal rounding] by3054+ // trimming a copy3055+ decNumberCopy(b, a);3056+ decTrim(b, set, 1, 1, &dropped); // [drops trailing zeros]3057+3058+ // Set Inexact and Rounded. The answer can only be exact if3059+ // it is short enough so that squaring it could fit in workp3060+ // digits, so this is the only (relatively rare) condition that3061+ // a careful check is needed3062+ if (b->digits*2-1 > workp) { // cannot fit3063+ status|=DEC_Inexact|DEC_Rounded;3064+ }3065+ else { // could be exact/unrounded3066+ uInt mstatus=0; // local status3067+ decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply3068+ if (mstatus&DEC_Overflow) { // result just won't fit3069+ status|=DEC_Inexact|DEC_Rounded;3070+ }3071+ else { // plausible3072+ decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs3073+ if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal3074+ else { // is Exact3075+ // here, dropped is the count of trailing zeros in 'a'3076+ // use closest exponent to ideal...3077+ Int todrop=ideal-a->exponent; // most that can be dropped3078+ if (todrop<0) status|=DEC_Rounded; // ideally would add 0s3079+ else { // unrounded3080+ // there are some to drop, but emax may not allow all3081+ Int maxexp=set->emax-set->digits+1;3082+ Int maxdrop=maxexp-a->exponent;3083+ if (todrop>maxdrop && set->clamp) { // apply clamping3084+ todrop=maxdrop;3085+ status|=DEC_Clamped;3086+ }3087+ if (dropped<todrop) { // clamp to those available3088+ todrop=dropped;3089+ status|=DEC_Clamped;3090+ }3091+ if (todrop>0) { // have some to drop3092+ decShiftToLeast(a->lsu, D2U(a->digits), todrop);3093+ a->exponent+=todrop; // maintain numerical value3094+ a->digits-=todrop; // new length3095+ }3096+ }3097+ }3098+ }3099+ }3100+3101+ // double-check Underflow, as perhaps the result could not have3102+ // been subnormal (initial argument too big), or it is now Exact3103+ if (status&DEC_Underflow) {3104+ Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent3105+ // check if truly subnormal3106+ #if DECEXTFLAG // DEC_Subnormal too3107+ if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);3108+ #else3109+ if (ae>=set->emin*2) status&=~DEC_Underflow;3110+ #endif3111+ // check if truly inexact3112+ if (!(status&DEC_Inexact)) status&=~DEC_Underflow;3113+ }3114+3115+ decNumberCopy(res, a); // a is now the result3116+ } while(0); // end protected3117+3118+ if (allocbuff!=NULL) free(allocbuff); // drop any storage used3119+ if (allocbufa!=NULL) free(allocbufa); // ..3120+ if (allocbufb!=NULL) free(allocbufb); // ..3121+ #if DECSUBSET3122+ if (allocrhs !=NULL) free(allocrhs); // ..3123+ #endif3124+ if (status!=0) decStatus(res, status, set);// then report status3125+ #if DECCHECK3126+ decCheckInexact(res, set);3127+ #endif3128+ return res;3129+ } // decNumberSquareRoot3130+3131+/* ------------------------------------------------------------------ */3132+/* decNumberSubtract -- subtract two Numbers */3133+/* */3134+/* This computes C = A - B */3135+/* */3136+/* res is C, the result. C may be A and/or B (e.g., X=X-X) */3137+/* lhs is A */3138+/* rhs is B */3139+/* set is the context */3140+/* */3141+/* C must have space for set->digits digits. */3142+/* ------------------------------------------------------------------ */3143+decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,3144+ const decNumber *rhs, decContext *set) {3145+ uInt status=0; // accumulator3146+3147+ decAddOp(res, lhs, rhs, set, DECNEG, &status);3148+ if (status!=0) decStatus(res, status, set);3149+ #if DECCHECK3150+ decCheckInexact(res, set);3151+ #endif3152+ return res;3153+ } // decNumberSubtract3154+3155+/* ------------------------------------------------------------------ */3156+/* decNumberToIntegralExact -- round-to-integral-value with InExact */3157+/* decNumberToIntegralValue -- round-to-integral-value */3158+/* */3159+/* res is the result */3160+/* rhs is input number */3161+/* set is the context */3162+/* */3163+/* res must have space for any value of rhs. */3164+/* */3165+/* This implements the IEEE special operators and therefore treats */3166+/* special values as valid. For finite numbers it returns */3167+/* rescale(rhs, 0) if rhs->exponent is <0. */3168+/* Otherwise the result is rhs (so no error is possible, except for */3169+/* sNaN). */3170+/* */3171+/* The context is used for rounding mode and status after sNaN, but */3172+/* the digits setting is ignored. The Exact version will signal */3173+/* Inexact if the result differs numerically from rhs; the other */3174+/* never signals Inexact. */3175+/* ------------------------------------------------------------------ */3176+decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,3177+ decContext *set) {3178+ decNumber dn;3179+ decContext workset; // working context3180+ uInt status=0; // accumulator3181+3182+ #if DECCHECK3183+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;3184+ #endif3185+3186+ // handle infinities and NaNs3187+ if (SPECIALARG) {3188+ if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity3189+ else decNaNs(res, rhs, NULL, set, &status); // a NaN3190+ }3191+ else { // finite3192+ // have a finite number; no error possible (res must be big enough)3193+ if (rhs->exponent>=0) return decNumberCopy(res, rhs);3194+ // that was easy, but if negative exponent there is work to do...3195+ workset=*set; // clone rounding, etc.3196+ workset.digits=rhs->digits; // no length rounding3197+ workset.traps=0; // no traps3198+ decNumberZero(&dn); // make a number with exponent 03199+ decNumberQuantize(res, rhs, &dn, &workset);3200+ status|=workset.status;3201+ }3202+ if (status!=0) decStatus(res, status, set);3203+ return res;3204+ } // decNumberToIntegralExact3205+3206+decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,3207+ decContext *set) {3208+ decContext workset=*set; // working context3209+ workset.traps=0; // no traps3210+ decNumberToIntegralExact(res, rhs, &workset);3211+ // this never affects set, except for sNaNs; NaN will have been set3212+ // or propagated already, so no need to call decStatus3213+ set->status|=workset.status&DEC_Invalid_operation;3214+ return res;3215+ } // decNumberToIntegralValue3216+3217+/* ------------------------------------------------------------------ */3218+/* decNumberXor -- XOR two Numbers, digitwise */3219+/* */3220+/* This computes C = A ^ B */3221+/* */3222+/* res is C, the result. C may be A and/or B (e.g., X=X^X) */3223+/* lhs is A */3224+/* rhs is B */3225+/* set is the context (used for result length and error report) */3226+/* */3227+/* C must have space for set->digits digits. */3228+/* */3229+/* Logical function restrictions apply (see above); a NaN is */3230+/* returned with Invalid_operation if a restriction is violated. */3231+/* ------------------------------------------------------------------ */3232+decNumber * decNumberXor(decNumber *res, const decNumber *lhs,3233+ const decNumber *rhs, decContext *set) {3234+ const Unit *ua, *ub; // -> operands3235+ const Unit *msua, *msub; // -> operand msus3236+ Unit *uc, *msuc; // -> result and its msu3237+ Int msudigs; // digits in res msu3238+ #if DECCHECK3239+ if (decCheckOperands(res, lhs, rhs, set)) return res;3240+ #endif3241+3242+ if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)3243+ || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {3244+ decStatus(res, DEC_Invalid_operation, set);3245+ return res;3246+ }3247+ // operands are valid3248+ ua=lhs->lsu; // bottom-up3249+ ub=rhs->lsu; // ..3250+ uc=res->lsu; // ..3251+ msua=ua+D2U(lhs->digits)-1; // -> msu of lhs3252+ msub=ub+D2U(rhs->digits)-1; // -> msu of rhs3253+ msuc=uc+D2U(set->digits)-1; // -> msu of result3254+ msudigs=MSUDIGITS(set->digits); // [faster than remainder]3255+ for (; uc<=msuc; ua++, ub++, uc++) { // Unit loop3256+ Unit a, b; // extract units3257+ if (ua>msua) a=0;3258+ else a=*ua;3259+ if (ub>msub) b=0;3260+ else b=*ub;3261+ *uc=0; // can now write back3262+ if (a|b) { // maybe 1 bits to examine3263+ Int i, j;3264+ // This loop could be unrolled and/or use BIN2BCD tables3265+ for (i=0; i<DECDPUN; i++) {3266+ if ((a^b)&1) *uc=*uc+(Unit)powers[i]; // effect XOR3267+ j=a%10;3268+ a=a/10;3269+ j|=b%10;3270+ b=b/10;3271+ if (j>1) {3272+ decStatus(res, DEC_Invalid_operation, set);3273+ return res;3274+ }3275+ if (uc==msuc && i==msudigs-1) break; // just did final digit3276+ } // each digit3277+ } // non-zero3278+ } // each unit3279+ // [here uc-1 is the msu of the result]3280+ res->digits=decGetDigits(res->lsu, uc-res->lsu);3281+ res->exponent=0; // integer3282+ res->bits=0; // sign=03283+ return res; // [no status to set]3284+ } // decNumberXor3285+3286+3287+/* ================================================================== */3288+/* Utility routines */3289+/* ================================================================== */3290+3291+/* ------------------------------------------------------------------ */3292+/* decNumberClass -- return the decClass of a decNumber */3293+/* dn -- the decNumber to test */3294+/* set -- the context to use for Emin */3295+/* returns the decClass enum */3296+/* ------------------------------------------------------------------ */3297+enum decClass decNumberClass(const decNumber *dn, decContext *set) {3298+ if (decNumberIsSpecial(dn)) {3299+ if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;3300+ if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;3301+ // must be an infinity3302+ if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;3303+ return DEC_CLASS_POS_INF;3304+ }3305+ // is finite3306+ if (decNumberIsNormal(dn, set)) { // most common3307+ if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;3308+ return DEC_CLASS_POS_NORMAL;3309+ }3310+ // is subnormal or zero3311+ if (decNumberIsZero(dn)) { // most common3312+ if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;3313+ return DEC_CLASS_POS_ZERO;3314+ }3315+ if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;3316+ return DEC_CLASS_POS_SUBNORMAL;3317+ } // decNumberClass3318+3319+/* ------------------------------------------------------------------ */3320+/* decNumberClassToString -- convert decClass to a string */3321+/* */3322+/* eclass is a valid decClass */3323+/* returns a constant string describing the class (max 13+1 chars) */3324+/* ------------------------------------------------------------------ */3325+const char *decNumberClassToString(enum decClass eclass) {3326+ if (eclass==DEC_CLASS_POS_NORMAL) return DEC_ClassString_PN;3327+ if (eclass==DEC_CLASS_NEG_NORMAL) return DEC_ClassString_NN;3328+ if (eclass==DEC_CLASS_POS_ZERO) return DEC_ClassString_PZ;3329+ if (eclass==DEC_CLASS_NEG_ZERO) return DEC_ClassString_NZ;3330+ if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;3331+ if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;3332+ if (eclass==DEC_CLASS_POS_INF) return DEC_ClassString_PI;3333+ if (eclass==DEC_CLASS_NEG_INF) return DEC_ClassString_NI;3334+ if (eclass==DEC_CLASS_QNAN) return DEC_ClassString_QN;3335+ if (eclass==DEC_CLASS_SNAN) return DEC_ClassString_SN;3336+ return DEC_ClassString_UN; // Unknown3337+ } // decNumberClassToString3338+3339+/* ------------------------------------------------------------------ */3340+/* decNumberCopy -- copy a number */3341+/* */3342+/* dest is the target decNumber */3343+/* src is the source decNumber */3344+/* returns dest */3345+/* */3346+/* (dest==src is allowed and is a no-op) */3347+/* All fields are updated as required. This is a utility operation, */3348+/* so special values are unchanged and no error is possible. */3349+/* ------------------------------------------------------------------ */3350+decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {3351+3352+ #if DECCHECK3353+ if (src==NULL) return decNumberZero(dest);3354+ #endif3355+3356+ if (dest==src) return dest; // no copy required3357+3358+ // Use explicit assignments here as structure assignment could copy3359+ // more than just the lsu (for small DECDPUN). This would not affect3360+ // the value of the results, but could disturb test harness spill3361+ // checking.3362+ dest->bits=src->bits;3363+ dest->exponent=src->exponent;3364+ dest->digits=src->digits;3365+ dest->lsu[0]=src->lsu[0];3366+ if (src->digits>DECDPUN) { // more Units to come3367+ const Unit *smsup, *s; // work3368+ Unit *d; // ..3369+ // memcpy for the remaining Units would be safe as they cannot3370+ // overlap. However, this explicit loop is faster in short cases.3371+ d=dest->lsu+1; // -> first destination3372+ smsup=src->lsu+D2U(src->digits); // -> source msu+13373+ for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;3374+ }3375+ return dest;3376+ } // decNumberCopy3377+3378+/* ------------------------------------------------------------------ */3379+/* decNumberCopyAbs -- quiet absolute value operator */3380+/* */3381+/* This sets C = abs(A) */3382+/* */3383+/* res is C, the result. C may be A */3384+/* rhs is A */3385+/* */3386+/* C must have space for set->digits digits. */3387+/* No exception or error can occur; this is a quiet bitwise operation.*/3388+/* See also decNumberAbs for a checking version of this. */3389+/* ------------------------------------------------------------------ */3390+decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {3391+ #if DECCHECK3392+ if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;3393+ #endif3394+ decNumberCopy(res, rhs);3395+ res->bits&=~DECNEG; // turn off sign3396+ return res;3397+ } // decNumberCopyAbs3398+3399+/* ------------------------------------------------------------------ */3400+/* decNumberCopyNegate -- quiet negate value operator */3401+/* */3402+/* This sets C = negate(A) */3403+/* */3404+/* res is C, the result. C may be A */3405+/* rhs is A */3406+/* */3407+/* C must have space for set->digits digits. */3408+/* No exception or error can occur; this is a quiet bitwise operation.*/3409+/* See also decNumberMinus for a checking version of this. */3410+/* ------------------------------------------------------------------ */3411+decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {3412+ #if DECCHECK3413+ if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;3414+ #endif3415+ decNumberCopy(res, rhs);3416+ res->bits^=DECNEG; // invert the sign3417+ return res;3418+ } // decNumberCopyNegate3419+3420+/* ------------------------------------------------------------------ */3421+/* decNumberCopySign -- quiet copy and set sign operator */3422+/* */3423+/* This sets C = A with the sign of B */3424+/* */3425+/* res is C, the result. C may be A */3426+/* lhs is A */3427+/* rhs is B */3428+/* */3429+/* C must have space for set->digits digits. */3430+/* No exception or error can occur; this is a quiet bitwise operation.*/3431+/* ------------------------------------------------------------------ */3432+decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,3433+ const decNumber *rhs) {3434+ uByte sign; // rhs sign3435+ #if DECCHECK3436+ if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;3437+ #endif3438+ sign=rhs->bits & DECNEG; // save sign bit3439+ decNumberCopy(res, lhs);3440+ res->bits&=~DECNEG; // clear the sign3441+ res->bits|=sign; // set from rhs3442+ return res;3443+ } // decNumberCopySign3444+3445+/* ------------------------------------------------------------------ */3446+/* decNumberGetBCD -- get the coefficient in BCD8 */3447+/* dn is the source decNumber */3448+/* bcd is the uInt array that will receive dn->digits BCD bytes, */3449+/* most-significant at offset 0 */3450+/* returns bcd */3451+/* */3452+/* bcd must have at least dn->digits bytes. No error is possible; if */3453+/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0. */3454+/* ------------------------------------------------------------------ */3455+uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {3456+ uByte *ub=bcd+dn->digits-1; // -> lsd3457+ const Unit *up=dn->lsu; // Unit pointer, -> lsu3458+3459+ #if DECDPUN==1 // trivial simple copy3460+ for (; ub>=bcd; ub--, up++) *ub=*up;3461+ #else // chopping needed3462+ uInt u=*up; // work3463+ uInt cut=DECDPUN; // downcounter through unit3464+ for (; ub>=bcd; ub--) {3465+ *ub=(uByte)(u%10); // [*6554 trick inhibits, here]3466+ u=u/10;3467+ cut--;3468+ if (cut>0) continue; // more in this unit3469+ up++;3470+ u=*up;3471+ cut=DECDPUN;3472+ }3473+ #endif3474+ return bcd;3475+ } // decNumberGetBCD3476+3477+/* ------------------------------------------------------------------ */3478+/* decNumberSetBCD -- set (replace) the coefficient from BCD8 */3479+/* dn is the target decNumber */3480+/* bcd is the uInt array that will source n BCD bytes, most- */3481+/* significant at offset 0 */3482+/* n is the number of digits in the source BCD array (bcd) */3483+/* returns dn */3484+/* */3485+/* dn must have space for at least n digits. No error is possible; */3486+/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1 */3487+/* and bcd[0] zero. */3488+/* ------------------------------------------------------------------ */3489+decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {3490+ Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [target pointer]3491+ const uByte *ub=bcd; // -> source msd3492+3493+ #if DECDPUN==1 // trivial simple copy3494+ for (; ub<bcd+n; ub++, up--) *up=*ub;3495+ #else // some assembly needed3496+ // calculate how many digits in msu, and hence first cut3497+ Int cut=MSUDIGITS(n); // [faster than remainder]3498+ for (;up>=dn->lsu; up--) { // each Unit from msu3499+ *up=0; // will take <=DECDPUN digits3500+ for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;3501+ cut=DECDPUN; // next Unit has all digits3502+ }3503+ #endif3504+ dn->digits=n; // set digit count3505+ return dn;3506+ } // decNumberSetBCD3507+3508+/* ------------------------------------------------------------------ */3509+/* decNumberIsNormal -- test normality of a decNumber */3510+/* dn is the decNumber to test */3511+/* set is the context to use for Emin */3512+/* returns 1 if |dn| is finite and >=Nmin, 0 otherwise */3513+/* ------------------------------------------------------------------ */3514+Int decNumberIsNormal(const decNumber *dn, decContext *set) {3515+ Int ae; // adjusted exponent3516+ #if DECCHECK3517+ if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;3518+ #endif3519+3520+ if (decNumberIsSpecial(dn)) return 0; // not finite3521+ if (decNumberIsZero(dn)) return 0; // not non-zero3522+3523+ ae=dn->exponent+dn->digits-1; // adjusted exponent3524+ if (ae<set->emin) return 0; // is subnormal3525+ return 1;3526+ } // decNumberIsNormal3527+3528+/* ------------------------------------------------------------------ */3529+/* decNumberIsSubnormal -- test subnormality of a decNumber */3530+/* dn is the decNumber to test */3531+/* set is the context to use for Emin */3532+/* returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise */3533+/* ------------------------------------------------------------------ */3534+Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {3535+ Int ae; // adjusted exponent3536+ #if DECCHECK3537+ if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;3538+ #endif3539+3540+ if (decNumberIsSpecial(dn)) return 0; // not finite3541+ if (decNumberIsZero(dn)) return 0; // not non-zero3542+3543+ ae=dn->exponent+dn->digits-1; // adjusted exponent3544+ if (ae<set->emin) return 1; // is subnormal3545+ return 0;3546+ } // decNumberIsSubnormal3547+3548+/* ------------------------------------------------------------------ */3549+/* decNumberTrim -- remove insignificant zeros */3550+/* */3551+/* dn is the number to trim */3552+/* returns dn */3553+/* */3554+/* All fields are updated as required. This is a utility operation, */3555+/* so special values are unchanged and no error is possible. The */3556+/* zeros are removed unconditionally. */3557+/* ------------------------------------------------------------------ */3558+decNumber * decNumberTrim(decNumber *dn) {3559+ Int dropped; // work3560+ decContext set; // ..3561+ #if DECCHECK3562+ if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;3563+ #endif3564+ decContextDefault(&set, DEC_INIT_BASE); // clamp=03565+ return decTrim(dn, &set, 0, 1, &dropped);3566+ } // decNumberTrim3567+3568+/* ------------------------------------------------------------------ */3569+/* decNumberVersion -- return the name and version of this module */3570+/* */3571+/* No error is possible. */3572+/* ------------------------------------------------------------------ */3573+const char * decNumberVersion(void) {3574+ return DECVERSION;3575+ } // decNumberVersion3576+3577+/* ------------------------------------------------------------------ */3578+/* decNumberZero -- set a number to 0 */3579+/* */3580+/* dn is the number to set, with space for one digit */3581+/* returns dn */3582+/* */3583+/* No error is possible. */3584+/* ------------------------------------------------------------------ */3585+// Memset is not used as it is much slower in some environments.3586+decNumber * decNumberZero(decNumber *dn) {3587+3588+ #if DECCHECK3589+ if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;3590+ #endif3591+3592+ dn->bits=0;3593+ dn->exponent=0;3594+ dn->digits=1;3595+ dn->lsu[0]=0;3596+ return dn;3597+ } // decNumberZero3598+3599+/* ================================================================== */3600+/* Local routines */3601+/* ================================================================== */3602+3603+/* ------------------------------------------------------------------ */3604+/* decToString -- lay out a number into a string */3605+/* */3606+/* dn is the number to lay out */3607+/* string is where to lay out the number */3608+/* eng is 1 if Engineering, 0 if Scientific */3609+/* */3610+/* string must be at least dn->digits+14 characters long */3611+/* No error is possible. */3612+/* */3613+/* Note that this routine can generate a -0 or 0.000. These are */3614+/* never generated in subset to-number or arithmetic, but can occur */3615+/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234). */3616+/* ------------------------------------------------------------------ */3617+// If DECCHECK is enabled the string "?" is returned if a number is3618+// invalid.3619+static void decToString(const decNumber *dn, char *string, Flag eng) {3620+ Int exp=dn->exponent; // local copy3621+ Int e; // E-part value3622+ Int pre; // digits before the '.'3623+ Int cut; // for counting digits in a Unit3624+ char *c=string; // work [output pointer]3625+ const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]3626+ uInt u, pow; // work3627+3628+ #if DECCHECK3629+ if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {3630+ strcpy(string, "?");3631+ return;}3632+ #endif3633+3634+ if (decNumberIsNegative(dn)) { // Negatives get a minus3635+ *c='-';3636+ c++;3637+ }3638+ if (dn->bits&DECSPECIAL) { // Is a special value3639+ if (decNumberIsInfinite(dn)) {3640+ strcpy(c, "Inf");3641+ strcpy(c+3, "inity");3642+ return;}3643+ // a NaN3644+ if (dn->bits&DECSNAN) { // signalling NaN3645+ *c='s';3646+ c++;3647+ }3648+ strcpy(c, "NaN");3649+ c+=3; // step past3650+ // if not a clean non-zero coefficient, that's all there is in a3651+ // NaN string3652+ if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;3653+ // [drop through to add integer]3654+ }3655+3656+ // calculate how many digits in msu, and hence first cut3657+ cut=MSUDIGITS(dn->digits); // [faster than remainder]3658+ cut--; // power of ten for digit3659+3660+ if (exp==0) { // simple integer [common fastpath]3661+ for (;up>=dn->lsu; up--) { // each Unit from msu3662+ u=*up; // contains DECDPUN digits to lay out3663+ for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);3664+ cut=DECDPUN-1; // next Unit has all digits3665+ }3666+ *c='\0'; // terminate the string3667+ return;}3668+3669+ /* non-0 exponent -- assume plain form */3670+ pre=dn->digits+exp; // digits before '.'3671+ e=0; // no E3672+ if ((exp>0) || (pre<-5)) { // need exponential form3673+ e=exp+dn->digits-1; // calculate E value3674+ pre=1; // assume one digit before '.'3675+ if (eng && (e!=0)) { // engineering: may need to adjust3676+ Int adj; // adjustment3677+ // The C remainder operator is undefined for negative numbers, so3678+ // a positive remainder calculation must be used here3679+ if (e<0) {3680+ adj=(-e)%3;3681+ if (adj!=0) adj=3-adj;3682+ }3683+ else { // e>03684+ adj=e%3;3685+ }3686+ e=e-adj;3687+ // if dealing with zero still produce an exponent which is a3688+ // multiple of three, as expected, but there will only be the3689+ // one zero before the E, still. Otherwise note the padding.3690+ if (!ISZERO(dn)) pre+=adj;3691+ else { // is zero3692+ if (adj!=0) { // 0.00Esnn needed3693+ e=e+3;3694+ pre=-(2-adj);3695+ }3696+ } // zero3697+ } // eng3698+ } // need exponent3699+3700+ /* lay out the digits of the coefficient, adding 0s and . as needed */3701+ u=*up;3702+ if (pre>0) { // xxx.xxx or xx00 (engineering) form3703+ Int n=pre;3704+ for (; pre>0; pre--, c++, cut--) {3705+ if (cut<0) { // need new Unit3706+ if (up==dn->lsu) break; // out of input digits (pre>digits)3707+ up--;3708+ cut=DECDPUN-1;3709+ u=*up;3710+ }3711+ TODIGIT(u, cut, c, pow);3712+ }3713+ if (n<dn->digits) { // more to come, after '.'3714+ *c='.'; c++;3715+ for (;; c++, cut--) {3716+ if (cut<0) { // need new Unit3717+ if (up==dn->lsu) break; // out of input digits3718+ up--;3719+ cut=DECDPUN-1;3720+ u=*up;3721+ }3722+ TODIGIT(u, cut, c, pow);3723+ }3724+ }3725+ else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed3726+ }3727+ else { // 0.xxx or 0.000xxx form3728+ *c='0'; c++;3729+ *c='.'; c++;3730+ for (; pre<0; pre++, c++) *c='0'; // add any 0's after '.'3731+ for (; ; c++, cut--) {3732+ if (cut<0) { // need new Unit3733+ if (up==dn->lsu) break; // out of input digits3734+ up--;3735+ cut=DECDPUN-1;3736+ u=*up;3737+ }3738+ TODIGIT(u, cut, c, pow);3739+ }3740+ }3741+3742+ /* Finally add the E-part, if needed. It will never be 0, has a3743+ base maximum and minimum of +999999999 through -999999999, but3744+ could range down to -1999999998 for anormal numbers */3745+ if (e!=0) {3746+ Flag had=0; // 1=had non-zero3747+ *c='E'; c++;3748+ *c='+'; c++; // assume positive3749+ u=e; // ..3750+ if (e<0) {3751+ *(c-1)='-'; // oops, need -3752+ u=-e; // uInt, please3753+ }3754+ // lay out the exponent [_itoa or equivalent is not ANSI C]3755+ for (cut=9; cut>=0; cut--) {3756+ TODIGIT(u, cut, c, pow);3757+ if (*c=='0' && !had) continue; // skip leading zeros3758+ had=1; // had non-03759+ c++; // step for next3760+ } // cut3761+ }3762+ *c='\0'; // terminate the string (all paths)3763+ return;3764+ } // decToString3765+3766+/* ------------------------------------------------------------------ */3767+/* decAddOp -- add/subtract operation */3768+/* */3769+/* This computes C = A + B */3770+/* */3771+/* res is C, the result. C may be A and/or B (e.g., X=X+X) */3772+/* lhs is A */3773+/* rhs is B */3774+/* set is the context */3775+/* negate is DECNEG if rhs should be negated, or 0 otherwise */3776+/* status accumulates status for the caller */3777+/* */3778+/* C must have space for set->digits digits. */3779+/* Inexact in status must be 0 for correct Exact zero sign in result */3780+/* ------------------------------------------------------------------ */3781+/* If possible, the coefficient is calculated directly into C. */3782+/* However, if: */3783+/* -- a digits+1 calculation is needed because the numbers are */3784+/* unaligned and span more than set->digits digits */3785+/* -- a carry to digits+1 digits looks possible */3786+/* -- C is the same as A or B, and the result would destructively */3787+/* overlap the A or B coefficient */3788+/* then the result must be calculated into a temporary buffer. In */3789+/* this case a local (stack) buffer is used if possible, and only if */3790+/* too long for that does malloc become the final resort. */3791+/* */3792+/* Misalignment is handled as follows: */3793+/* Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp. */3794+/* BPad: Apply the padding by a combination of shifting (whole */3795+/* units) and multiplication (part units). */3796+/* */3797+/* Addition, especially x=x+1, is speed-critical. */3798+/* The static buffer is larger than might be expected to allow for */3799+/* calls from higher-level funtions (notable exp). */3800+/* ------------------------------------------------------------------ */3801+static decNumber * decAddOp(decNumber *res, const decNumber *lhs,3802+ const decNumber *rhs, decContext *set,3803+ uByte negate, uInt *status) {3804+ #if DECSUBSET3805+ decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated3806+ decNumber *allocrhs=NULL; // .., rhs3807+ #endif3808+ Int rhsshift; // working shift (in Units)3809+ Int maxdigits; // longest logical length3810+ Int mult; // multiplier3811+ Int residue; // rounding accumulator3812+ uByte bits; // result bits3813+ Flag diffsign; // non-0 if arguments have different sign3814+ Unit *acc; // accumulator for result3815+ Unit accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many3816+ // allocations when called from3817+ // other operations, notable exp]3818+ Unit *allocacc=NULL; // -> allocated acc buffer, iff allocated3819+ Int reqdigits=set->digits; // local copy; requested DIGITS3820+ Int padding; // work3821+3822+ #if DECCHECK3823+ if (decCheckOperands(res, lhs, rhs, set)) return res;3824+ #endif3825+3826+ do { // protect allocated storage3827+ #if DECSUBSET3828+ if (!set->extended) {3829+ // reduce operands and set lostDigits status, as needed3830+ if (lhs->digits>reqdigits) {3831+ alloclhs=decRoundOperand(lhs, set, status);3832+ if (alloclhs==NULL) break;3833+ lhs=alloclhs;3834+ }3835+ if (rhs->digits>reqdigits) {3836+ allocrhs=decRoundOperand(rhs, set, status);3837+ if (allocrhs==NULL) break;3838+ rhs=allocrhs;3839+ }3840+ }3841+ #endif3842+ // [following code does not require input rounding]3843+3844+ // note whether signs differ [used all paths]3845+ diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);3846+3847+ // handle infinities and NaNs3848+ if (SPECIALARGS) { // a special bit set3849+ if (SPECIALARGS & (DECSNAN | DECNAN)) // a NaN3850+ decNaNs(res, lhs, rhs, set, status);3851+ else { // one or two infinities3852+ if (decNumberIsInfinite(lhs)) { // LHS is infinity3853+ // two infinities with different signs is invalid3854+ if (decNumberIsInfinite(rhs) && diffsign) {3855+ *status|=DEC_Invalid_operation;3856+ break;3857+ }3858+ bits=lhs->bits & DECNEG; // get sign from LHS3859+ }3860+ else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity3861+ bits|=DECINF;3862+ decNumberZero(res);3863+ res->bits=bits; // set +/- infinity3864+ } // an infinity3865+ break;3866+ }3867+3868+ // Quick exit for add 0s; return the non-0, modified as need be3869+ if (ISZERO(lhs)) {3870+ Int adjust; // work3871+ Int lexp=lhs->exponent; // save in case LHS==RES3872+ bits=lhs->bits; // ..3873+ residue=0; // clear accumulator3874+ decCopyFit(res, rhs, set, &residue, status); // copy (as needed)3875+ res->bits^=negate; // flip if rhs was negated3876+ #if DECSUBSET3877+ if (set->extended) { // exponents on zeros count3878+ #endif3879+ // exponent will be the lower of the two3880+ adjust=lexp-res->exponent; // adjustment needed [if -ve]3881+ if (ISZERO(res)) { // both 0: special IEEE 754 rules3882+ if (adjust<0) res->exponent=lexp; // set exponent3883+ // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -03884+ if (diffsign) {3885+ if (set->round!=DEC_ROUND_FLOOR) res->bits=0;3886+ else res->bits=DECNEG; // preserve 0 sign3887+ }3888+ }3889+ else { // non-0 res3890+ if (adjust<0) { // 0-padding needed3891+ if ((res->digits-adjust)>set->digits) {3892+ adjust=res->digits-set->digits; // to fit exactly3893+ *status|=DEC_Rounded; // [but exact]3894+ }3895+ res->digits=decShiftToMost(res->lsu, res->digits, -adjust);3896+ res->exponent+=adjust; // set the exponent.3897+ }3898+ } // non-0 res3899+ #if DECSUBSET3900+ } // extended3901+ #endif3902+ decFinish(res, set, &residue, status); // clean and finalize3903+ break;}3904+3905+ if (ISZERO(rhs)) { // [lhs is non-zero]3906+ Int adjust; // work3907+ Int rexp=rhs->exponent; // save in case RHS==RES3908+ bits=rhs->bits; // be clean3909+ residue=0; // clear accumulator3910+ decCopyFit(res, lhs, set, &residue, status); // copy (as needed)3911+ #if DECSUBSET3912+ if (set->extended) { // exponents on zeros count3913+ #endif3914+ // exponent will be the lower of the two3915+ // [0-0 case handled above]3916+ adjust=rexp-res->exponent; // adjustment needed [if -ve]3917+ if (adjust<0) { // 0-padding needed3918+ if ((res->digits-adjust)>set->digits) {3919+ adjust=res->digits-set->digits; // to fit exactly3920+ *status|=DEC_Rounded; // [but exact]3921+ }3922+ res->digits=decShiftToMost(res->lsu, res->digits, -adjust);3923+ res->exponent+=adjust; // set the exponent.3924+ }3925+ #if DECSUBSET3926+ } // extended3927+ #endif3928+ decFinish(res, set, &residue, status); // clean and finalize3929+ break;}3930+3931+ // [NB: both fastpath and mainpath code below assume these cases3932+ // (notably 0-0) have already been handled]3933+3934+ // calculate the padding needed to align the operands3935+ padding=rhs->exponent-lhs->exponent;3936+3937+ // Fastpath cases where the numbers are aligned and normal, the RHS3938+ // is all in one unit, no operand rounding is needed, and no carry,3939+ // lengthening, or borrow is needed3940+ if (padding==03941+ && rhs->digits<=DECDPUN3942+ && rhs->exponent>=set->emin // [some normals drop through]3943+ && rhs->exponent<=set->emax-set->digits+1 // [could clamp]3944+ && rhs->digits<=reqdigits3945+ && lhs->digits<=reqdigits) {3946+ Int partial=*lhs->lsu;3947+ if (!diffsign) { // adding3948+ partial+=*rhs->lsu;3949+ if ((partial<=DECDPUNMAX) // result fits in unit3950+ && (lhs->digits>=DECDPUN || // .. and no digits-count change3951+ partial<(Int)powers[lhs->digits])) { // ..3952+ if (res!=lhs) decNumberCopy(res, lhs); // not in place3953+ *res->lsu=(Unit)partial; // [copy could have overwritten RHS]3954+ break;3955+ }3956+ // else drop out for careful add3957+ }3958+ else { // signs differ3959+ partial-=*rhs->lsu;3960+ if (partial>0) { // no borrow needed, and non-0 result3961+ if (res!=lhs) decNumberCopy(res, lhs); // not in place3962+ *res->lsu=(Unit)partial;3963+ // this could have reduced digits [but result>0]3964+ res->digits=decGetDigits(res->lsu, D2U(res->digits));3965+ break;3966+ }3967+ // else drop out for careful subtract3968+ }3969+ }3970+3971+ // Now align (pad) the lhs or rhs so they can be added or3972+ // subtracted, as necessary. If one number is much larger than3973+ // the other (that is, if in plain form there is a least one3974+ // digit between the lowest digit of one and the highest of the3975+ // other) padding with up to DIGITS-1 trailing zeros may be3976+ // needed; then apply rounding (as exotic rounding modes may be3977+ // affected by the residue).3978+ rhsshift=0; // rhs shift to left (padding) in Units3979+ bits=lhs->bits; // assume sign is that of LHS3980+ mult=1; // likely multiplier3981+3982+ // [if padding==0 the operands are aligned; no padding is needed]3983+ if (padding!=0) {3984+ // some padding needed; always pad the RHS, as any required3985+ // padding can then be effected by a simple combination of3986+ // shifts and a multiply3987+ Flag swapped=0;3988+ if (padding<0) { // LHS needs the padding3989+ const decNumber *t;3990+ padding=-padding; // will be +ve3991+ bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS3992+ t=lhs; lhs=rhs; rhs=t;3993+ swapped=1;3994+ }3995+3996+ // If, after pad, rhs would be longer than lhs by digits+1 or3997+ // more then lhs cannot affect the answer, except as a residue,3998+ // so only need to pad up to a length of DIGITS+1.3999+ if (rhs->digits+padding > lhs->digits+reqdigits+1) {4000+ // The RHS is sufficient4001+ // for residue use the relative sign indication...4002+ Int shift=reqdigits-rhs->digits; // left shift needed4003+ residue=1; // residue for rounding4004+ if (diffsign) residue=-residue; // signs differ4005+ // copy, shortening if necessary4006+ decCopyFit(res, rhs, set, &residue, status);4007+ // if it was already shorter, then need to pad with zeros4008+ if (shift>0) {4009+ res->digits=decShiftToMost(res->lsu, res->digits, shift);4010+ res->exponent-=shift; // adjust the exponent.4011+ }4012+ // flip the result sign if unswapped and rhs was negated4013+ if (!swapped) res->bits^=negate;4014+ decFinish(res, set, &residue, status); // done4015+ break;}4016+4017+ // LHS digits may affect result4018+ rhsshift=D2U(padding+1)-1; // this much by Unit shift ..4019+ mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication4020+ } // padding needed4021+4022+ if (diffsign) mult=-mult; // signs differ4023+4024+ // determine the longer operand4025+ maxdigits=rhs->digits+padding; // virtual length of RHS4026+ if (lhs->digits>maxdigits) maxdigits=lhs->digits;4027+4028+ // Decide on the result buffer to use; if possible place directly4029+ // into result.4030+ acc=res->lsu; // assume add direct to result4031+ // If destructive overlap, or the number is too long, or a carry or4032+ // borrow to DIGITS+1 might be possible, a buffer must be used.4033+ // [Might be worth more sophisticated tests when maxdigits==reqdigits]4034+ if ((maxdigits>=reqdigits) // is, or could be, too large4035+ || (res==rhs && rhsshift>0)) { // destructive overlap4036+ // buffer needed, choose it; units for maxdigits digits will be4037+ // needed, +1 Unit for carry or borrow4038+ Int need=D2U(maxdigits)+1;4039+ acc=accbuff; // assume use local buffer4040+ if (need*sizeof(Unit)>sizeof(accbuff)) {4041+ // printf("malloc add %ld %ld\n", need, sizeof(accbuff));4042+ allocacc=(Unit *)malloc(need*sizeof(Unit));4043+ if (allocacc==NULL) { // hopeless -- abandon4044+ *status|=DEC_Insufficient_storage;4045+ break;}4046+ acc=allocacc;4047+ }4048+ }4049+4050+ res->bits=(uByte)(bits&DECNEG); // it's now safe to overwrite..4051+ res->exponent=lhs->exponent; // .. operands (even if aliased)4052+4053+ #if DECTRACE4054+ decDumpAr('A', lhs->lsu, D2U(lhs->digits));4055+ decDumpAr('B', rhs->lsu, D2U(rhs->digits));4056+ printf(" :h: %ld %ld\n", rhsshift, mult);4057+ #endif4058+4059+ // add [A+B*m] or subtract [A+B*(-m)]4060+ res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),4061+ rhs->lsu, D2U(rhs->digits),4062+ rhsshift, acc, mult)4063+ *DECDPUN; // [units -> digits]4064+ if (res->digits<0) { // borrowed...4065+ res->digits=-res->digits;4066+ res->bits^=DECNEG; // flip the sign4067+ }4068+ #if DECTRACE4069+ decDumpAr('+', acc, D2U(res->digits));4070+ #endif4071+4072+ // If a buffer was used the result must be copied back, possibly4073+ // shortening. (If no buffer was used then the result must have4074+ // fit, so can't need rounding and residue must be 0.)4075+ residue=0; // clear accumulator4076+ if (acc!=res->lsu) {4077+ #if DECSUBSET4078+ if (set->extended) { // round from first significant digit4079+ #endif4080+ // remove leading zeros that were added due to rounding up to4081+ // integral Units -- before the test for rounding.4082+ if (res->digits>reqdigits)4083+ res->digits=decGetDigits(acc, D2U(res->digits));4084+ decSetCoeff(res, set, acc, res->digits, &residue, status);4085+ #if DECSUBSET4086+ }4087+ else { // subset arithmetic rounds from original significant digit4088+ // May have an underestimate. This only occurs when both4089+ // numbers fit in DECDPUN digits and are padding with a4090+ // negative multiple (-10, -100...) and the top digit(s) become4091+ // 0. (This only matters when using X3.274 rules where the4092+ // leading zero could be included in the rounding.)4093+ if (res->digits<maxdigits) {4094+ *(acc+D2U(res->digits))=0; // ensure leading 0 is there4095+ res->digits=maxdigits;4096+ }4097+ else {4098+ // remove leading zeros that added due to rounding up to4099+ // integral Units (but only those in excess of the original4100+ // maxdigits length, unless extended) before test for rounding.4101+ if (res->digits>reqdigits) {4102+ res->digits=decGetDigits(acc, D2U(res->digits));4103+ if (res->digits<maxdigits) res->digits=maxdigits;4104+ }4105+ }4106+ decSetCoeff(res, set, acc, res->digits, &residue, status);4107+ // Now apply rounding if needed before removing leading zeros.4108+ // This is safe because subnormals are not a possibility4109+ if (residue!=0) {4110+ decApplyRound(res, set, residue, status);4111+ residue=0; // did what needed to be done4112+ }4113+ } // subset4114+ #endif4115+ } // used buffer4116+4117+ // strip leading zeros [these were left on in case of subset subtract]4118+ res->digits=decGetDigits(res->lsu, D2U(res->digits));4119+4120+ // apply checks and rounding4121+ decFinish(res, set, &residue, status);4122+4123+ // "When the sum of two operands with opposite signs is exactly4124+ // zero, the sign of that sum shall be '+' in all rounding modes4125+ // except round toward -Infinity, in which mode that sign shall be4126+ // '-'." [Subset zeros also never have '-', set by decFinish.]4127+ if (ISZERO(res) && diffsign4128+ #if DECSUBSET4129+ && set->extended4130+ #endif4131+ && (*status&DEC_Inexact)==0) {4132+ if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG; // sign -4133+ else res->bits&=~DECNEG; // sign +4134+ }4135+ } while(0); // end protected4136+4137+ if (allocacc!=NULL) free(allocacc); // drop any storage used4138+ #if DECSUBSET4139+ if (allocrhs!=NULL) free(allocrhs); // ..4140+ if (alloclhs!=NULL) free(alloclhs); // ..4141+ #endif4142+ return res;4143+ } // decAddOp4144+4145+/* ------------------------------------------------------------------ */4146+/* decDivideOp -- division operation */4147+/* */4148+/* This routine performs the calculations for all four division */4149+/* operators (divide, divideInteger, remainder, remainderNear). */4150+/* */4151+/* C=A op B */4152+/* */4153+/* res is C, the result. C may be A and/or B (e.g., X=X/X) */4154+/* lhs is A */4155+/* rhs is B */4156+/* set is the context */4157+/* op is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively. */4158+/* status is the usual accumulator */4159+/* */4160+/* C must have space for set->digits digits. */4161+/* */4162+/* ------------------------------------------------------------------ */4163+/* The underlying algorithm of this routine is the same as in the */4164+/* 1981 S/370 implementation, that is, non-restoring long division */4165+/* with bi-unit (rather than bi-digit) estimation for each unit */4166+/* multiplier. In this pseudocode overview, complications for the */4167+/* Remainder operators and division residues for exact rounding are */4168+/* omitted for clarity. */4169+/* */4170+/* Prepare operands and handle special values */4171+/* Test for x/0 and then 0/x */4172+/* Exp =Exp1 - Exp2 */4173+/* Exp =Exp +len(var1) -len(var2) */4174+/* Sign=Sign1 * Sign2 */4175+/* Pad accumulator (Var1) to double-length with 0's (pad1) */4176+/* Pad Var2 to same length as Var1 */4177+/* msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round */4178+/* have=0 */4179+/* Do until (have=digits+1 OR residue=0) */4180+/* if exp<0 then if integer divide/residue then leave */4181+/* this_unit=0 */4182+/* Do forever */4183+/* compare numbers */4184+/* if <0 then leave inner_loop */4185+/* if =0 then (* quick exit without subtract *) do */4186+/* this_unit=this_unit+1; output this_unit */4187+/* leave outer_loop; end */4188+/* Compare lengths of numbers (mantissae): */4189+/* If same then tops2=msu2pair -- {units 1&2 of var2} */4190+/* else tops2=msu2plus -- {0, unit 1 of var2} */4191+/* tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */4192+/* mult=tops1/tops2 -- Good and safe guess at divisor */4193+/* if mult=0 then mult=1 */4194+/* this_unit=this_unit+mult */4195+/* subtract */4196+/* end inner_loop */4197+/* if have\=0 | this_unit\=0 then do */4198+/* output this_unit */4199+/* have=have+1; end */4200+/* var2=var2/10 */4201+/* exp=exp-1 */4202+/* end outer_loop */4203+/* exp=exp+1 -- set the proper exponent */4204+/* if have=0 then generate answer=0 */4205+/* Return (Result is defined by Var1) */4206+/* */4207+/* ------------------------------------------------------------------ */4208+/* Two working buffers are needed during the division; one (digits+ */4209+/* 1) to accumulate the result, and the other (up to 2*digits+1) for */4210+/* long subtractions. These are acc and var1 respectively. */4211+/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/4212+/* The static buffers may be larger than might be expected to allow */4213+/* for calls from higher-level funtions (notable exp). */4214+/* ------------------------------------------------------------------ */4215+static decNumber * decDivideOp(decNumber *res,4216+ const decNumber *lhs, const decNumber *rhs,4217+ decContext *set, Flag op, uInt *status) {4218+ #if DECSUBSET4219+ decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated4220+ decNumber *allocrhs=NULL; // .., rhs4221+ #endif4222+ Unit accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer4223+ Unit *acc=accbuff; // -> accumulator array for result4224+ Unit *allocacc=NULL; // -> allocated buffer, iff allocated4225+ Unit *accnext; // -> where next digit will go4226+ Int acclength; // length of acc needed [Units]4227+ Int accunits; // count of units accumulated4228+ Int accdigits; // count of digits accumulated4229+4230+ Unit varbuff[SD2U(DECBUFFER*2+DECDPUN)]; // buffer for var14231+ Unit *var1=varbuff; // -> var1 array for long subtraction4232+ Unit *varalloc=NULL; // -> allocated buffer, iff used4233+ Unit *msu1; // -> msu of var14234+4235+ const Unit *var2; // -> var2 array4236+ const Unit *msu2; // -> msu of var24237+ Int msu2plus; // msu2 plus one [does not vary]4238+ eInt msu2pair; // msu2 pair plus one [does not vary]4239+4240+ Int var1units, var2units; // actual lengths4241+ Int var2ulen; // logical length (units)4242+ Int var1initpad=0; // var1 initial padding (digits)4243+ Int maxdigits; // longest LHS or required acc length4244+ Int mult; // multiplier for subtraction4245+ Unit thisunit; // current unit being accumulated4246+ Int residue; // for rounding4247+ Int reqdigits=set->digits; // requested DIGITS4248+ Int exponent; // working exponent4249+ Int maxexponent=0; // DIVIDE maximum exponent if unrounded4250+ uByte bits; // working sign4251+ Unit *target; // work4252+ const Unit *source; // ..4253+ uInt const *pow; // ..4254+ Int shift, cut; // ..4255+ #if DECSUBSET4256+ Int dropped; // work4257+ #endif4258+4259+ #if DECCHECK4260+ if (decCheckOperands(res, lhs, rhs, set)) return res;4261+ #endif4262+4263+ do { // protect allocated storage4264+ #if DECSUBSET4265+ if (!set->extended) {4266+ // reduce operands and set lostDigits status, as needed4267+ if (lhs->digits>reqdigits) {4268+ alloclhs=decRoundOperand(lhs, set, status);4269+ if (alloclhs==NULL) break;4270+ lhs=alloclhs;4271+ }4272+ if (rhs->digits>reqdigits) {4273+ allocrhs=decRoundOperand(rhs, set, status);4274+ if (allocrhs==NULL) break;4275+ rhs=allocrhs;4276+ }4277+ }4278+ #endif4279+ // [following code does not require input rounding]4280+4281+ bits=(lhs->bits^rhs->bits)&DECNEG; // assumed sign for divisions4282+4283+ // handle infinities and NaNs4284+ if (SPECIALARGS) { // a special bit set4285+ if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs4286+ decNaNs(res, lhs, rhs, set, status);4287+ break;4288+ }4289+ // one or two infinities4290+ if (decNumberIsInfinite(lhs)) { // LHS (dividend) is infinite4291+ if (decNumberIsInfinite(rhs) || // two infinities are invalid ..4292+ op & (REMAINDER | REMNEAR)) { // as is remainder of infinity4293+ *status|=DEC_Invalid_operation;4294+ break;4295+ }4296+ // [Note that infinity/0 raises no exceptions]4297+ decNumberZero(res);4298+ res->bits=bits|DECINF; // set +/- infinity4299+ break;4300+ }4301+ else { // RHS (divisor) is infinite4302+ residue=0;4303+ if (op&(REMAINDER|REMNEAR)) {4304+ // result is [finished clone of] lhs4305+ decCopyFit(res, lhs, set, &residue, status);4306+ }4307+ else { // a division4308+ decNumberZero(res);4309+ res->bits=bits; // set +/- zero4310+ // for DIVIDEINT the exponent is always 0. For DIVIDE, result4311+ // is a 0 with infinitely negative exponent, clamped to minimum4312+ if (op&DIVIDE) {4313+ res->exponent=set->emin-set->digits+1;4314+ *status|=DEC_Clamped;4315+ }4316+ }4317+ decFinish(res, set, &residue, status);4318+ break;4319+ }4320+ }4321+4322+ // handle 0 rhs (x/0)4323+ if (ISZERO(rhs)) { // x/0 is always exceptional4324+ if (ISZERO(lhs)) {4325+ decNumberZero(res); // [after lhs test]4326+ *status|=DEC_Division_undefined;// 0/0 will become NaN4327+ }4328+ else {4329+ decNumberZero(res);4330+ if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;4331+ else {4332+ *status|=DEC_Division_by_zero; // x/04333+ res->bits=bits|DECINF; // .. is +/- Infinity4334+ }4335+ }4336+ break;}4337+4338+ // handle 0 lhs (0/x)4339+ if (ISZERO(lhs)) { // 0/x [x!=0]4340+ #if DECSUBSET4341+ if (!set->extended) decNumberZero(res);4342+ else {4343+ #endif4344+ if (op&DIVIDE) {4345+ residue=0;4346+ exponent=lhs->exponent-rhs->exponent; // ideal exponent4347+ decNumberCopy(res, lhs); // [zeros always fit]4348+ res->bits=bits; // sign as computed4349+ res->exponent=exponent; // exponent, too4350+ decFinalize(res, set, &residue, status); // check exponent4351+ }4352+ else if (op&DIVIDEINT) {4353+ decNumberZero(res); // integer 04354+ res->bits=bits; // sign as computed4355+ }4356+ else { // a remainder4357+ exponent=rhs->exponent; // [save in case overwrite]4358+ decNumberCopy(res, lhs); // [zeros always fit]4359+ if (exponent<res->exponent) res->exponent=exponent; // use lower4360+ }4361+ #if DECSUBSET4362+ }4363+ #endif4364+ break;}4365+4366+ // Precalculate exponent. This starts off adjusted (and hence fits4367+ // in 31 bits) and becomes the usual unadjusted exponent as the4368+ // division proceeds. The order of evaluation is important, here,4369+ // to avoid wrap.4370+ exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);4371+4372+ // If the working exponent is -ve, then some quick exits are4373+ // possible because the quotient is known to be <14374+ // [for REMNEAR, it needs to be < -1, as -0.5 could need work]4375+ if (exponent<0 && !(op==DIVIDE)) {4376+ if (op&DIVIDEINT) {4377+ decNumberZero(res); // integer part is 04378+ #if DECSUBSET4379+ if (set->extended)4380+ #endif4381+ res->bits=bits; // set +/- zero4382+ break;}4383+ // fastpath remainders so long as the lhs has the smaller4384+ // (or equal) exponent4385+ if (lhs->exponent<=rhs->exponent) {4386+ if (op&REMAINDER || exponent<-1) {4387+ // It is REMAINDER or safe REMNEAR; result is [finished4388+ // clone of] lhs (r = x - 0*y)4389+ residue=0;4390+ decCopyFit(res, lhs, set, &residue, status);4391+ decFinish(res, set, &residue, status);4392+ break;4393+ }4394+ // [unsafe REMNEAR drops through]4395+ }4396+ } // fastpaths4397+4398+ /* Long (slow) division is needed; roll up the sleeves... */4399+4400+ // The accumulator will hold the quotient of the division.4401+ // If it needs to be too long for stack storage, then allocate.4402+ acclength=D2U(reqdigits+DECDPUN); // in Units4403+ if (acclength*sizeof(Unit)>sizeof(accbuff)) {4404+ // printf("malloc dvacc %ld units\n", acclength);4405+ allocacc=(Unit *)malloc(acclength*sizeof(Unit));4406+ if (allocacc==NULL) { // hopeless -- abandon4407+ *status|=DEC_Insufficient_storage;4408+ break;}4409+ acc=allocacc; // use the allocated space4410+ }4411+4412+ // var1 is the padded LHS ready for subtractions.4413+ // If it needs to be too long for stack storage, then allocate.4414+ // The maximum units needed for var1 (long subtraction) is:4415+ // Enough for4416+ // (rhs->digits+reqdigits-1) -- to allow full slide to right4417+ // or (lhs->digits) -- to allow for long lhs4418+ // whichever is larger4419+ // +1 -- for rounding of slide to right4420+ // +1 -- for leading 0s4421+ // +1 -- for pre-adjust if a remainder or DIVIDEINT4422+ // [Note: unused units do not participate in decUnitAddSub data]4423+ maxdigits=rhs->digits+reqdigits-1;4424+ if (lhs->digits>maxdigits) maxdigits=lhs->digits;4425+ var1units=D2U(maxdigits)+2;4426+ // allocate a guard unit above msu1 for REMAINDERNEAR4427+ if (!(op&DIVIDE)) var1units++;4428+ if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {4429+ // printf("malloc dvvar %ld units\n", var1units+1);4430+ varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));4431+ if (varalloc==NULL) { // hopeless -- abandon4432+ *status|=DEC_Insufficient_storage;4433+ break;}4434+ var1=varalloc; // use the allocated space4435+ }4436+4437+ // Extend the lhs and rhs to full long subtraction length. The lhs4438+ // is truly extended into the var1 buffer, with 0 padding, so a4439+ // subtract in place is always possible. The rhs (var2) has4440+ // virtual padding (implemented by decUnitAddSub).4441+ // One guard unit was allocated above msu1 for rem=rem+rem in4442+ // REMAINDERNEAR.4443+ msu1=var1+var1units-1; // msu of var14444+ source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array4445+ for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;4446+ for (; target>=var1; target--) *target=0;4447+4448+ // rhs (var2) is left-aligned with var1 at the start4449+ var2ulen=var1units; // rhs logical length (units)4450+ var2units=D2U(rhs->digits); // rhs actual length (units)4451+ var2=rhs->lsu; // -> rhs array4452+ msu2=var2+var2units-1; // -> msu of var2 [never changes]4453+ // now set up the variables which will be used for estimating the4454+ // multiplication factor. If these variables are not exact, add4455+ // 1 to make sure that the multiplier is never overestimated.4456+ msu2plus=*msu2; // it's value ..4457+ if (var2units>1) msu2plus++; // .. +1 if any more4458+ msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..4459+ if (var2units>1) { // .. [else treat 2nd as 0]4460+ msu2pair+=*(msu2-1); // ..4461+ if (var2units>2) msu2pair++; // .. +1 if any more4462+ }4463+4464+ // The calculation is working in units, which may have leading zeros,4465+ // but the exponent was calculated on the assumption that they are4466+ // both left-aligned. Adjust the exponent to compensate: add the4467+ // number of leading zeros in var1 msu and subtract those in var2 msu.4468+ // [This is actually done by counting the digits and negating, as4469+ // lead1=DECDPUN-digits1, and similarly for lead2.]4470+ for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;4471+ for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;4472+4473+ // Now, if doing an integer divide or remainder, ensure that4474+ // the result will be Unit-aligned. To do this, shift the var14475+ // accumulator towards least if need be. (It's much easier to4476+ // do this now than to reassemble the residue afterwards, if4477+ // doing a remainder.) Also ensure the exponent is not negative.4478+ if (!(op&DIVIDE)) {4479+ Unit *u; // work4480+ // save the initial 'false' padding of var1, in digits4481+ var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;4482+ // Determine the shift to do.4483+ if (exponent<0) cut=-exponent;4484+ else cut=DECDPUN-exponent%DECDPUN;4485+ decShiftToLeast(var1, var1units, cut);4486+ exponent+=cut; // maintain numerical value4487+ var1initpad-=cut; // .. and reduce padding4488+ // clean any most-significant units which were just emptied4489+ for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;4490+ } // align4491+ else { // is DIVIDE4492+ maxexponent=lhs->exponent-rhs->exponent; // save4493+ // optimization: if the first iteration will just produce 0,4494+ // preadjust to skip it [valid for DIVIDE only]4495+ if (*msu1<*msu2) {4496+ var2ulen--; // shift down4497+ exponent-=DECDPUN; // update the exponent4498+ }4499+ }4500+4501+ // ---- start the long-division loops ------------------------------4502+ accunits=0; // no units accumulated yet4503+ accdigits=0; // .. or digits4504+ accnext=acc+acclength-1; // -> msu of acc [NB: allows digits+1]4505+ for (;;) { // outer forever loop4506+ thisunit=0; // current unit assumed 04507+ // find the next unit4508+ for (;;) { // inner forever loop4509+ // strip leading zero units [from either pre-adjust or from4510+ // subtract last time around]. Leave at least one unit.4511+ for (; *msu1==0 && msu1>var1; msu1--) var1units--;4512+4513+ if (var1units<var2ulen) break; // var1 too low for subtract4514+ if (var1units==var2ulen) { // unit-by-unit compare needed4515+ // compare the two numbers, from msu4516+ const Unit *pv1, *pv2;4517+ Unit v2; // units to compare4518+ pv2=msu2; // -> msu4519+ for (pv1=msu1; ; pv1--, pv2--) {4520+ // v1=*pv1 -- always OK4521+ v2=0; // assume in padding4522+ if (pv2>=var2) v2=*pv2; // in range4523+ if (*pv1!=v2) break; // no longer the same4524+ if (pv1==var1) break; // done; leave pv1 as is4525+ }4526+ // here when all inspected or a difference seen4527+ if (*pv1<v2) break; // var1 too low to subtract4528+ if (*pv1==v2) { // var1 == var24529+ // reach here if var1 and var2 are identical; subtraction4530+ // would increase digit by one, and the residue will be 0 so4531+ // the calculation is done; leave the loop with residue=0.4532+ thisunit++; // as though subtracted4533+ *var1=0; // set var1 to 04534+ var1units=1; // ..4535+ break; // from inner4536+ } // var1 == var24537+ // *pv1>v2. Prepare for real subtraction; the lengths are equal4538+ // Estimate the multiplier (there's always a msu1-1)...4539+ // Bring in two units of var2 to provide a good estimate.4540+ mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);4541+ } // lengths the same4542+ else { // var1units > var2ulen, so subtraction is safe4543+ // The var2 msu is one unit towards the lsu of the var1 msu,4544+ // so only one unit for var2 can be used.4545+ mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);4546+ }4547+ if (mult==0) mult=1; // must always be at least 14548+ // subtraction needed; var1 is > var24549+ thisunit=(Unit)(thisunit+mult); // accumulate4550+ // subtract var1-var2, into var1; only the overlap needs4551+ // processing, as this is an in-place calculation4552+ shift=var2ulen-var2units;4553+ #if DECTRACE4554+ decDumpAr('1', &var1[shift], var1units-shift);4555+ decDumpAr('2', var2, var2units);4556+ printf("m=%ld\n", -mult);4557+ #endif4558+ decUnitAddSub(&var1[shift], var1units-shift,4559+ var2, var2units, 0,4560+ &var1[shift], -mult);4561+ #if DECTRACE4562+ decDumpAr('#', &var1[shift], var1units-shift);4563+ #endif4564+ // var1 now probably has leading zeros; these are removed at the4565+ // top of the inner loop.4566+ } // inner loop4567+4568+ // The next unit has been calculated in full; unless it's a4569+ // leading zero, add to acc4570+ if (accunits!=0 || thisunit!=0) { // is first or non-zero4571+ *accnext=thisunit; // store in accumulator4572+ // account exactly for the new digits4573+ if (accunits==0) {4574+ accdigits++; // at least one4575+ for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;4576+ }4577+ else accdigits+=DECDPUN;4578+ accunits++; // update count4579+ accnext--; // ready for next4580+ if (accdigits>reqdigits) break; // have enough digits4581+ }4582+4583+ // if the residue is zero, the operation is done (unless divide4584+ // or divideInteger and still not enough digits yet)4585+ if (*var1==0 && var1units==1) { // residue is 04586+ if (op&(REMAINDER|REMNEAR)) break;4587+ if ((op&DIVIDE) && (exponent<=maxexponent)) break;4588+ // [drop through if divideInteger]4589+ }4590+ // also done enough if calculating remainder or integer4591+ // divide and just did the last ('units') unit4592+ if (exponent==0 && !(op&DIVIDE)) break;4593+4594+ // to get here, var1 is less than var2, so divide var2 by the per-4595+ // Unit power of ten and go for the next digit4596+ var2ulen--; // shift down4597+ exponent-=DECDPUN; // update the exponent4598+ } // outer loop4599+4600+ // ---- division is complete ---------------------------------------4601+ // here: acc has at least reqdigits+1 of good results (or fewer4602+ // if early stop), starting at accnext+1 (its lsu)4603+ // var1 has any residue at the stopping point4604+ // accunits is the number of digits collected in acc4605+ if (accunits==0) { // acc is 04606+ accunits=1; // show have a unit ..4607+ accdigits=1; // ..4608+ *accnext=0; // .. whose value is 04609+ }4610+ else accnext++; // back to last placed4611+ // accnext now -> lowest unit of result4612+4613+ residue=0; // assume no residue4614+ if (op&DIVIDE) {4615+ // record the presence of any residue, for rounding4616+ if (*var1!=0 || var1units>1) residue=1;4617+ else { // no residue4618+ // Had an exact division; clean up spurious trailing 0s.4619+ // There will be at most DECDPUN-1, from the final multiply,4620+ // and then only if the result is non-0 (and even) and the4621+ // exponent is 'loose'.4622+ #if DECDPUN>14623+ Unit lsu=*accnext;4624+ if (!(lsu&0x01) && (lsu!=0)) {4625+ // count the trailing zeros4626+ Int drop=0;4627+ for (;; drop++) { // [will terminate because lsu!=0]4628+ if (exponent>=maxexponent) break; // don't chop real 0s4629+ #if DECDPUN<=44630+ if ((lsu-QUOT10(lsu, drop+1)4631+ *powers[drop+1])!=0) break; // found non-0 digit4632+ #else4633+ if (lsu%powers[drop+1]!=0) break; // found non-0 digit4634+ #endif4635+ exponent++;4636+ }4637+ if (drop>0) {4638+ accunits=decShiftToLeast(accnext, accunits, drop);4639+ accdigits=decGetDigits(accnext, accunits);4640+ accunits=D2U(accdigits);4641+ // [exponent was adjusted in the loop]4642+ }4643+ } // neither odd nor 04644+ #endif4645+ } // exact divide4646+ } // divide4647+ else /* op!=DIVIDE */ {4648+ // check for coefficient overflow4649+ if (accdigits+exponent>reqdigits) {4650+ *status|=DEC_Division_impossible;4651+ break;4652+ }4653+ if (op & (REMAINDER|REMNEAR)) {4654+ // [Here, the exponent will be 0, because var1 was adjusted4655+ // appropriately.]4656+ Int postshift; // work4657+ Flag wasodd=0; // integer was odd4658+ Unit *quotlsu; // for save4659+ Int quotdigits; // ..4660+4661+ bits=lhs->bits; // remainder sign is always as lhs4662+4663+ // Fastpath when residue is truly 0 is worthwhile [and4664+ // simplifies the code below]4665+ if (*var1==0 && var1units==1) { // residue is 04666+ Int exp=lhs->exponent; // save min(exponents)4667+ if (rhs->exponent<exp) exp=rhs->exponent;4668+ decNumberZero(res); // 0 coefficient4669+ #if DECSUBSET4670+ if (set->extended)4671+ #endif4672+ res->exponent=exp; // .. with proper exponent4673+ res->bits=(uByte)(bits&DECNEG); // [cleaned]4674+ decFinish(res, set, &residue, status); // might clamp4675+ break;4676+ }4677+ // note if the quotient was odd4678+ if (*accnext & 0x01) wasodd=1; // acc is odd4679+ quotlsu=accnext; // save in case need to reinspect4680+ quotdigits=accdigits; // ..4681+4682+ // treat the residue, in var1, as the value to return, via acc4683+ // calculate the unused zero digits. This is the smaller of:4684+ // var1 initial padding (saved above)4685+ // var2 residual padding, which happens to be given by:4686+ postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;4687+ // [the 'exponent' term accounts for the shifts during divide]4688+ if (var1initpad<postshift) postshift=var1initpad;4689+4690+ // shift var1 the requested amount, and adjust its digits4691+ var1units=decShiftToLeast(var1, var1units, postshift);4692+ accnext=var1;4693+ accdigits=decGetDigits(var1, var1units);4694+ accunits=D2U(accdigits);4695+4696+ exponent=lhs->exponent; // exponent is smaller of lhs & rhs4697+ if (rhs->exponent<exponent) exponent=rhs->exponent;4698+4699+ // Now correct the result if doing remainderNear; if it4700+ // (looking just at coefficients) is > rhs/2, or == rhs/2 and4701+ // the integer was odd then the result should be rem-rhs.4702+ if (op&REMNEAR) {4703+ Int compare, tarunits; // work4704+ Unit *up; // ..4705+ // calculate remainder*2 into the var1 buffer (which has4706+ // 'headroom' of an extra unit and hence enough space)4707+ // [a dedicated 'double' loop would be faster, here]4708+ tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,4709+ 0, accnext, 1);4710+ // decDumpAr('r', accnext, tarunits);4711+4712+ // Here, accnext (var1) holds tarunits Units with twice the4713+ // remainder's coefficient, which must now be compared to the4714+ // RHS. The remainder's exponent may be smaller than the RHS's.4715+ compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),4716+ rhs->exponent-exponent);4717+ if (compare==BADINT) { // deep trouble4718+ *status|=DEC_Insufficient_storage;4719+ break;}4720+4721+ // now restore the remainder by dividing by two; the lsu4722+ // is known to be even.4723+ for (up=accnext; up<accnext+tarunits; up++) {4724+ Int half; // half to add to lower unit4725+ half=*up & 0x01;4726+ *up/=2; // [shift]4727+ if (!half) continue;4728+ *(up-1)+=(DECDPUNMAX+1)/2;4729+ }4730+ // [accunits still describes the original remainder length]4731+4732+ if (compare>0 || (compare==0 && wasodd)) { // adjustment needed4733+ Int exp, expunits, exprem; // work4734+ // This is effectively causing round-up of the quotient,4735+ // so if it was the rare case where it was full and all4736+ // nines, it would overflow and hence division-impossible4737+ // should be raised4738+ Flag allnines=0; // 1 if quotient all nines4739+ if (quotdigits==reqdigits) { // could be borderline4740+ for (up=quotlsu; ; up++) {4741+ if (quotdigits>DECDPUN) {4742+ if (*up!=DECDPUNMAX) break;// non-nines4743+ }4744+ else { // this is the last Unit4745+ if (*up==powers[quotdigits]-1) allnines=1;4746+ break;4747+ }4748+ quotdigits-=DECDPUN; // checked those digits4749+ } // up4750+ } // borderline check4751+ if (allnines) {4752+ *status|=DEC_Division_impossible;4753+ break;}4754+4755+ // rem-rhs is needed; the sign will invert. Again, var14756+ // can safely be used for the working Units array.4757+ exp=rhs->exponent-exponent; // RHS padding needed4758+ // Calculate units and remainder from exponent.4759+ expunits=exp/DECDPUN;4760+ exprem=exp%DECDPUN;4761+ // subtract [A+B*(-m)]; the result will always be negative4762+ accunits=-decUnitAddSub(accnext, accunits,4763+ rhs->lsu, D2U(rhs->digits),4764+ expunits, accnext, -(Int)powers[exprem]);4765+ accdigits=decGetDigits(accnext, accunits); // count digits exactly4766+ accunits=D2U(accdigits); // and recalculate the units for copy4767+ // [exponent is as for original remainder]4768+ bits^=DECNEG; // flip the sign4769+ }4770+ } // REMNEAR4771+ } // REMAINDER or REMNEAR4772+ } // not DIVIDE4773+4774+ // Set exponent and bits4775+ res->exponent=exponent;4776+ res->bits=(uByte)(bits&DECNEG); // [cleaned]4777+4778+ // Now the coefficient.4779+ decSetCoeff(res, set, accnext, accdigits, &residue, status);4780+4781+ decFinish(res, set, &residue, status); // final cleanup4782+4783+ #if DECSUBSET4784+ // If a divide then strip trailing zeros if subset [after round]4785+ if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);4786+ #endif4787+ } while(0); // end protected4788+4789+ if (varalloc!=NULL) free(varalloc); // drop any storage used4790+ if (allocacc!=NULL) free(allocacc); // ..4791+ #if DECSUBSET4792+ if (allocrhs!=NULL) free(allocrhs); // ..4793+ if (alloclhs!=NULL) free(alloclhs); // ..4794+ #endif4795+ return res;4796+ } // decDivideOp4797+4798+/* ------------------------------------------------------------------ */4799+/* decMultiplyOp -- multiplication operation */4800+/* */4801+/* This routine performs the multiplication C=A x B. */4802+/* */4803+/* res is C, the result. C may be A and/or B (e.g., X=X*X) */4804+/* lhs is A */4805+/* rhs is B */4806+/* set is the context */4807+/* status is the usual accumulator */4808+/* */4809+/* C must have space for set->digits digits. */4810+/* */4811+/* ------------------------------------------------------------------ */4812+/* 'Classic' multiplication is used rather than Karatsuba, as the */4813+/* latter would give only a minor improvement for the short numbers */4814+/* expected to be handled most (and uses much more memory). */4815+/* */4816+/* There are two major paths here: the general-purpose ('old code') */4817+/* path which handles all DECDPUN values, and a fastpath version */4818+/* which is used if 64-bit ints are available, DECDPUN<=4, and more */4819+/* than two calls to decUnitAddSub would be made. */4820+/* */4821+/* The fastpath version lumps units together into 8-digit or 9-digit */4822+/* chunks, and also uses a lazy carry strategy to minimise expensive */4823+/* 64-bit divisions. The chunks are then broken apart again into */4824+/* units for continuing processing. Despite this overhead, the */4825+/* fastpath can speed up some 16-digit operations by 10x (and much */4826+/* more for higher-precision calculations). */4827+/* */4828+/* A buffer always has to be used for the accumulator; in the */4829+/* fastpath, buffers are also always needed for the chunked copies of */4830+/* of the operand coefficients. */4831+/* Static buffers are larger than needed just for multiply, to allow */4832+/* for calls from other operations (notably exp). */4833+/* ------------------------------------------------------------------ */4834+#define FASTMUL (DECUSE64 && DECDPUN<5)4835+static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,4836+ const decNumber *rhs, decContext *set,4837+ uInt *status) {4838+ Int accunits; // Units of accumulator in use4839+ Int exponent; // work4840+ Int residue=0; // rounding residue4841+ uByte bits; // result sign4842+ Unit *acc; // -> accumulator Unit array4843+ Int needbytes; // size calculator4844+ void *allocacc=NULL; // -> allocated accumulator, iff allocated4845+ Unit accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,4846+ // *4 for calls from other operations)4847+ const Unit *mer, *mermsup; // work4848+ Int madlength; // Units in multiplicand4849+ Int shift; // Units to shift multiplicand by4850+4851+ #if FASTMUL4852+ // if DECDPUN is 1 or 3 work in base 10**9, otherwise4853+ // (DECDPUN is 2 or 4) then work in base 10**84854+ #if DECDPUN & 1 // odd4855+ #define FASTBASE 1000000000 // base4856+ #define FASTDIGS 9 // digits in base4857+ #define FASTLAZY 18 // carry resolution point [1->18]4858+ #else4859+ #define FASTBASE 1000000004860+ #define FASTDIGS 84861+ #define FASTLAZY 1844 // carry resolution point [1->1844]4862+ #endif4863+ // three buffers are used, two for chunked copies of the operands4864+ // (base 10**8 or base 10**9) and one base 2**64 accumulator with4865+ // lazy carry evaluation4866+ uInt zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)4867+ uInt *zlhi=zlhibuff; // -> lhs array4868+ uInt *alloclhi=NULL; // -> allocated buffer, iff allocated4869+ uInt zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)4870+ uInt *zrhi=zrhibuff; // -> rhs array4871+ uInt *allocrhi=NULL; // -> allocated buffer, iff allocated4872+ uLong zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)4873+ // [allocacc is shared for both paths, as only one will run]4874+ uLong *zacc=zaccbuff; // -> accumulator array for exact result4875+ #if DECDPUN==14876+ Int zoff; // accumulator offset4877+ #endif4878+ uInt *lip, *rip; // item pointers4879+ uInt *lmsi, *rmsi; // most significant items4880+ Int ilhs, irhs, iacc; // item counts in the arrays4881+ Int lazy; // lazy carry counter4882+ uLong lcarry; // uLong carry4883+ uInt carry; // carry (NB not uLong)4884+ Int count; // work4885+ const Unit *cup; // ..4886+ Unit *up; // ..4887+ uLong *lp; // ..4888+ Int p; // ..4889+ #endif4890+4891+ #if DECSUBSET4892+ decNumber *alloclhs=NULL; // -> allocated buffer, iff allocated4893+ decNumber *allocrhs=NULL; // -> allocated buffer, iff allocated4894+ #endif4895+4896+ #if DECCHECK4897+ if (decCheckOperands(res, lhs, rhs, set)) return res;4898+ #endif4899+4900+ // precalculate result sign4901+ bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);4902+4903+ // handle infinities and NaNs4904+ if (SPECIALARGS) { // a special bit set4905+ if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs4906+ decNaNs(res, lhs, rhs, set, status);4907+ return res;}4908+ // one or two infinities; Infinity * 0 is invalid4909+ if (((lhs->bits & DECINF)==0 && ISZERO(lhs))4910+ ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {4911+ *status|=DEC_Invalid_operation;4912+ return res;}4913+ decNumberZero(res);4914+ res->bits=bits|DECINF; // infinity4915+ return res;}4916+4917+ // For best speed, as in DMSRCN [the original Rexx numerics4918+ // module], use the shorter number as the multiplier (rhs) and4919+ // the longer as the multiplicand (lhs) to minimise the number of4920+ // adds (partial products)4921+ if (lhs->digits<rhs->digits) { // swap...4922+ const decNumber *hold=lhs;4923+ lhs=rhs;4924+ rhs=hold;4925+ }4926+4927+ do { // protect allocated storage4928+ #if DECSUBSET4929+ if (!set->extended) {4930+ // reduce operands and set lostDigits status, as needed4931+ if (lhs->digits>set->digits) {4932+ alloclhs=decRoundOperand(lhs, set, status);4933+ if (alloclhs==NULL) break;4934+ lhs=alloclhs;4935+ }4936+ if (rhs->digits>set->digits) {4937+ allocrhs=decRoundOperand(rhs, set, status);4938+ if (allocrhs==NULL) break;4939+ rhs=allocrhs;4940+ }4941+ }4942+ #endif4943+ // [following code does not require input rounding]4944+4945+ #if FASTMUL // fastpath can be used4946+ // use the fast path if there are enough digits in the shorter4947+ // operand to make the setup and takedown worthwhile4948+ #define NEEDTWO (DECDPUN*2) // within two decUnitAddSub calls4949+ if (rhs->digits>NEEDTWO) { // use fastpath...4950+ // calculate the number of elements in each array4951+ ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]4952+ irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..4953+ iacc=ilhs+irhs;4954+4955+ // allocate buffers if required, as usual4956+ needbytes=ilhs*sizeof(uInt);4957+ if (needbytes>(Int)sizeof(zlhibuff)) {4958+ alloclhi=(uInt *)malloc(needbytes);4959+ zlhi=alloclhi;}4960+ needbytes=irhs*sizeof(uInt);4961+ if (needbytes>(Int)sizeof(zrhibuff)) {4962+ allocrhi=(uInt *)malloc(needbytes);4963+ zrhi=allocrhi;}4964+4965+ // Allocating the accumulator space needs a special case when4966+ // DECDPUN=1 because when converting the accumulator to Units4967+ // after the multiplication each 8-byte item becomes 9 1-byte4968+ // units. Therefore iacc extra bytes are needed at the front4969+ // (rounded up to a multiple of 8 bytes), and the uLong4970+ // accumulator starts offset the appropriate number of units4971+ // to the right to avoid overwrite during the unchunking.4972+ needbytes=iacc*sizeof(uLong);4973+ #if DECDPUN==14974+ zoff=(iacc+7)/8; // items to offset by4975+ needbytes+=zoff*8;4976+ #endif4977+ if (needbytes>(Int)sizeof(zaccbuff)) {4978+ allocacc=(uLong *)malloc(needbytes);4979+ zacc=(uLong *)allocacc;}4980+ if (zlhi==NULL||zrhi==NULL||zacc==NULL) {4981+ *status|=DEC_Insufficient_storage;4982+ break;}4983+4984+ acc=(Unit *)zacc; // -> target Unit array4985+ #if DECDPUN==14986+ zacc+=zoff; // start uLong accumulator to right4987+ #endif4988+4989+ // assemble the chunked copies of the left and right sides4990+ for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)4991+ for (p=0, *lip=0; p<FASTDIGS && count>0;4992+ p+=DECDPUN, cup++, count-=DECDPUN)4993+ *lip+=*cup*powers[p];4994+ lmsi=lip-1; // save -> msi4995+ for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)4996+ for (p=0, *rip=0; p<FASTDIGS && count>0;4997+ p+=DECDPUN, cup++, count-=DECDPUN)4998+ *rip+=*cup*powers[p];4999+ rmsi=rip-1; // save -> msi5000+5001+ // zero the accumulator5002+ for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;5003+5004+ /* Start the multiplication */5005+ // Resolving carries can dominate the cost of accumulating the5006+ // partial products, so this is only done when necessary.5007+ // Each uLong item in the accumulator can hold values up to5008+ // 2**64-1, and each partial product can be as large as5009+ // (10**FASTDIGS-1)**2. When FASTDIGS=9, this can be added to5010+ // itself 18.4 times in a uLong without overflowing, so during5011+ // the main calculation resolution is carried out every 18th5012+ // add -- every 162 digits. Similarly, when FASTDIGS=8, the5013+ // partial products can be added to themselves 1844.6 times in5014+ // a uLong without overflowing, so intermediate carry5015+ // resolution occurs only every 14752 digits. Hence for common5016+ // short numbers usually only the one final carry resolution5017+ // occurs.5018+ // (The count is set via FASTLAZY to simplify experiments to5019+ // measure the value of this approach: a 35% improvement on a5020+ // [34x34] multiply.)5021+ lazy=FASTLAZY; // carry delay count5022+ for (rip=zrhi; rip<=rmsi; rip++) { // over each item in rhs5023+ lp=zacc+(rip-zrhi); // where to add the lhs5024+ for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs5025+ *lp+=(uLong)(*lip)*(*rip); // [this should in-line]5026+ } // lip loop5027+ lazy--;5028+ if (lazy>0 && rip!=rmsi) continue;5029+ lazy=FASTLAZY; // reset delay count5030+ // spin up the accumulator resolving overflows5031+ for (lp=zacc; lp<zacc+iacc; lp++) {5032+ if (*lp<FASTBASE) continue; // it fits5033+ lcarry=*lp/FASTBASE; // top part [slow divide]5034+ // lcarry can exceed 2**32-1, so check again; this check5035+ // and occasional extra divide (slow) is well worth it, as5036+ // it allows FASTLAZY to be increased to 18 rather than 45037+ // in the FASTDIGS=9 case5038+ if (lcarry<FASTBASE) carry=(uInt)lcarry; // [usual]5039+ else { // two-place carry [fairly rare]5040+ uInt carry2=(uInt)(lcarry/FASTBASE); // top top part5041+ *(lp+2)+=carry2; // add to item+25042+ *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]5043+ carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]5044+ }5045+ *(lp+1)+=carry; // add to item above [inline]5046+ *lp-=((uLong)FASTBASE*carry); // [inline]5047+ } // carry resolution5048+ } // rip loop5049+5050+ // The multiplication is complete; time to convert back into5051+ // units. This can be done in-place in the accumulator and in5052+ // 32-bit operations, because carries were resolved after the5053+ // final add. This needs N-1 divides and multiplies for5054+ // each item in the accumulator (which will become up to N5055+ // units, where 2<=N<=9).5056+ for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {5057+ uInt item=(uInt)*lp; // decapitate to uInt5058+ for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {5059+ uInt part=item/(DECDPUNMAX+1);5060+ *up=(Unit)(item-(part*(DECDPUNMAX+1)));5061+ item=part;5062+ } // p5063+ *up=(Unit)item; up++; // [final needs no division]5064+ } // lp5065+ accunits=up-acc; // count of units5066+ }5067+ else { // here to use units directly, without chunking ['old code']5068+ #endif5069+5070+ // if accumulator will be too long for local storage, then allocate5071+ acc=accbuff; // -> assume buffer for accumulator5072+ needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);5073+ if (needbytes>(Int)sizeof(accbuff)) {5074+ allocacc=(Unit *)malloc(needbytes);5075+ if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}5076+ acc=(Unit *)allocacc; // use the allocated space5077+ }5078+5079+ /* Now the main long multiplication loop */5080+ // Unlike the equivalent in the IBM Java implementation, there5081+ // is no advantage in calculating from msu to lsu. So, do it5082+ // by the book, as it were.5083+ // Each iteration calculates ACC=ACC+MULTAND*MULT5084+ accunits=1; // accumulator starts at '0'5085+ *acc=0; // .. (lsu=0)5086+ shift=0; // no multiplicand shift at first5087+ madlength=D2U(lhs->digits); // this won't change5088+ mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier5089+5090+ for (mer=rhs->lsu; mer<mermsup; mer++) {5091+ // Here, *mer is the next Unit in the multiplier to use5092+ // If non-zero [optimization] add it...5093+ if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,5094+ lhs->lsu, madlength, 0,5095+ &acc[shift], *mer)5096+ + shift;5097+ else { // extend acc with a 0; it will be used shortly5098+ *(acc+accunits)=0; // [this avoids length of <=0 later]5099+ accunits++;5100+ }5101+ // multiply multiplicand by 10**DECDPUN for next Unit to left5102+ shift++; // add this for 'logical length'5103+ } // n5104+ #if FASTMUL5105+ } // unchunked units5106+ #endif5107+ // common end-path5108+ #if DECTRACE5109+ decDumpAr('*', acc, accunits); // Show exact result5110+ #endif5111+5112+ // acc now contains the exact result of the multiplication,5113+ // possibly with a leading zero unit; build the decNumber from5114+ // it, noting if any residue5115+ res->bits=bits; // set sign5116+ res->digits=decGetDigits(acc, accunits); // count digits exactly5117+5118+ // There can be a 31-bit wrap in calculating the exponent.5119+ // This can only happen if both input exponents are negative and5120+ // both their magnitudes are large. If there was a wrap, set a5121+ // safe very negative exponent, from which decFinalize() will5122+ // raise a hard underflow shortly.5123+ exponent=lhs->exponent+rhs->exponent; // calculate exponent5124+ if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)5125+ exponent=-2*DECNUMMAXE; // force underflow5126+ res->exponent=exponent; // OK to overwrite now5127+5128+5129+ // Set the coefficient. If any rounding, residue records5130+ decSetCoeff(res, set, acc, res->digits, &residue, status);5131+ decFinish(res, set, &residue, status); // final cleanup5132+ } while(0); // end protected5133+5134+ if (allocacc!=NULL) free(allocacc); // drop any storage used5135+ #if DECSUBSET5136+ if (allocrhs!=NULL) free(allocrhs); // ..5137+ if (alloclhs!=NULL) free(alloclhs); // ..5138+ #endif5139+ #if FASTMUL5140+ if (allocrhi!=NULL) free(allocrhi); // ..5141+ if (alloclhi!=NULL) free(alloclhi); // ..5142+ #endif5143+ return res;5144+ } // decMultiplyOp5145+5146+/* ------------------------------------------------------------------ */5147+/* decExpOp -- effect exponentiation */5148+/* */5149+/* This computes C = exp(A) */5150+/* */5151+/* res is C, the result. C may be A */5152+/* rhs is A */5153+/* set is the context; note that rounding mode has no effect */5154+/* */5155+/* C must have space for set->digits digits. status is updated but */5156+/* not set. */5157+/* */5158+/* Restrictions: */5159+/* */5160+/* digits, emax, and -emin in the context must be less than */5161+/* 2*DEC_MAX_MATH (1999998), and the rhs must be within these */5162+/* bounds or a zero. This is an internal routine, so these */5163+/* restrictions are contractual and not enforced. */5164+/* */5165+/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */5166+/* almost always be correctly rounded, but may be up to 1 ulp in */5167+/* error in rare cases. */5168+/* */5169+/* Finite results will always be full precision and Inexact, except */5170+/* when A is a zero or -Infinity (giving 1 or 0 respectively). */5171+/* ------------------------------------------------------------------ */5172+/* This approach used here is similar to the algorithm described in */5173+/* */5174+/* Variable Precision Exponential Function, T. E. Hull and */5175+/* A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */5176+/* pp79-91, ACM, June 1986. */5177+/* */5178+/* with the main difference being that the iterations in the series */5179+/* evaluation are terminated dynamically (which does not require the */5180+/* extra variable-precision variables which are expensive in this */5181+/* context). */5182+/* */5183+/* The error analysis in Hull & Abrham's paper applies except for the */5184+/* round-off error accumulation during the series evaluation. This */5185+/* code does not precalculate the number of iterations and so cannot */5186+/* use Horner's scheme. Instead, the accumulation is done at double- */5187+/* precision, which ensures that the additions of the terms are exact */5188+/* and do not accumulate round-off (and any round-off errors in the */5189+/* terms themselves move 'to the right' faster than they can */5190+/* accumulate). This code also extends the calculation by allowing, */5191+/* in the spirit of other decNumber operators, the input to be more */5192+/* precise than the result (the precision used is based on the more */5193+/* precise of the input or requested result). */5194+/* */5195+/* Implementation notes: */5196+/* */5197+/* 1. This is separated out as decExpOp so it can be called from */5198+/* other Mathematical functions (notably Ln) with a wider range */5199+/* than normal. In particular, it can handle the slightly wider */5200+/* (double) range needed by Ln (which has to be able to calculate */5201+/* exp(-x) where x can be the tiniest number (Ntiny). */5202+/* */5203+/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop */5204+/* iterations by appoximately a third with additional (although */5205+/* diminishing) returns as the range is reduced to even smaller */5206+/* fractions. However, h (the power of 10 used to correct the */5207+/* result at the end, see below) must be kept <=8 as otherwise */5208+/* the final result cannot be computed. Hence the leverage is a */5209+/* sliding value (8-h), where potentially the range is reduced */5210+/* more for smaller values. */5211+/* */5212+/* The leverage that can be applied in this way is severely */5213+/* limited by the cost of the raise-to-the power at the end, */5214+/* which dominates when the number of iterations is small (less */5215+/* than ten) or when rhs is short. As an example, the adjustment */5216+/* x**10,000,000 needs 31 multiplications, all but one full-width. */5217+/* */5218+/* 3. The restrictions (especially precision) could be raised with */5219+/* care, but the full decNumber range seems very hard within the */5220+/* 32-bit limits. */5221+/* */5222+/* 4. The working precisions for the static buffers are twice the */5223+/* obvious size to allow for calls from decNumberPower. */5224+/* ------------------------------------------------------------------ */5225+decNumber * decExpOp(decNumber *res, const decNumber *rhs,5226+ decContext *set, uInt *status) {5227+ uInt ignore=0; // working status5228+ Int h; // adjusted exponent for 0.xxxx5229+ Int p; // working precision5230+ Int residue; // rounding residue5231+ uInt needbytes; // for space calculations5232+ const decNumber *x=rhs; // (may point to safe copy later)5233+ decContext aset, tset, dset; // working contexts5234+ Int comp; // work5235+5236+ // the argument is often copied to normalize it, so (unusually) it5237+ // is treated like other buffers, using DECBUFFER, +1 in case5238+ // DECBUFFER is 05239+ decNumber bufr[D2N(DECBUFFER*2+1)];5240+ decNumber *allocrhs=NULL; // non-NULL if rhs buffer allocated5241+5242+ // the working precision will be no more than set->digits+8+15243+ // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER5244+ // is 0 (and twice that for the accumulator)5245+5246+ // buffer for t, term (working precision plus)5247+ decNumber buft[D2N(DECBUFFER*2+9+1)];5248+ decNumber *allocbuft=NULL; // -> allocated buft, iff allocated5249+ decNumber *t=buft; // term5250+ // buffer for a, accumulator (working precision * 2), at least 95251+ decNumber bufa[D2N(DECBUFFER*4+18+1)];5252+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated5253+ decNumber *a=bufa; // accumulator5254+ // decNumber for the divisor term; this needs at most 9 digits5255+ // and so can be fixed size [16 so can use standard context]5256+ decNumber bufd[D2N(16)];5257+ decNumber *d=bufd; // divisor5258+ decNumber numone; // constant 15259+5260+ #if DECCHECK5261+ Int iterations=0; // for later sanity check5262+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;5263+ #endif5264+5265+ do { // protect allocated storage5266+ if (SPECIALARG) { // handle infinities and NaNs5267+ if (decNumberIsInfinite(rhs)) { // an infinity5268+ if (decNumberIsNegative(rhs)) // -Infinity -> +05269+ decNumberZero(res);5270+ else decNumberCopy(res, rhs); // +Infinity -> self5271+ }5272+ else decNaNs(res, rhs, NULL, set, status); // a NaN5273+ break;}5274+5275+ if (ISZERO(rhs)) { // zeros -> exact 15276+ decNumberZero(res); // make clean 15277+ *res->lsu=1; // ..5278+ break;} // [no status to set]5279+5280+ // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path5281+ // positive and negative tiny cases which will result in inexact5282+ // 1. This also allows the later add-accumulate to always be5283+ // exact (because its length will never be more than twice the5284+ // working precision).5285+ // The comparator (tiny) needs just one digit, so use the5286+ // decNumber d for it (reused as the divisor, etc., below); its5287+ // exponent is such that if x is positive it will have5288+ // set->digits-1 zeros between the decimal point and the digit,5289+ // which is 4, and if x is negative one more zero there as the5290+ // more precise result will be of the form 0.9999999 rather than5291+ // 1.0000001. Hence, tiny will be 0.0000004 if digits=7 and x>05292+ // or 0.00000004 if digits=7 and x<0. If RHS not larger than5293+ // this then the result will be 1.0000005294+ decNumberZero(d); // clean5295+ *d->lsu=4; // set 4 ..5296+ d->exponent=-set->digits; // * 10**(-d)5297+ if (decNumberIsNegative(rhs)) d->exponent--; // negative case5298+ comp=decCompare(d, rhs, 1); // signless compare5299+ if (comp==BADINT) {5300+ *status|=DEC_Insufficient_storage;5301+ break;}5302+ if (comp>=0) { // rhs < d5303+ Int shift=set->digits-1;5304+ decNumberZero(res); // set 15305+ *res->lsu=1; // ..5306+ res->digits=decShiftToMost(res->lsu, 1, shift);5307+ res->exponent=-shift; // make 1.0000...5308+ *status|=DEC_Inexact | DEC_Rounded; // .. inexactly5309+ break;} // tiny5310+5311+ // set up the context to be used for calculating a, as this is5312+ // used on both paths below5313+ decContextDefault(&aset, DEC_INIT_DECIMAL64);5314+ // accumulator bounds are as requested (could underflow)5315+ aset.emax=set->emax; // usual bounds5316+ aset.emin=set->emin; // ..5317+ aset.clamp=0; // and no concrete format5318+5319+ // calculate the adjusted (Hull & Abrham) exponent (where the5320+ // decimal point is just to the left of the coefficient msd)5321+ h=rhs->exponent+rhs->digits;5322+ // if h>8 then 10**h cannot be calculated safely; however, when5323+ // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at5324+ // least 6.59E+4342944, so (due to the restriction on Emax/Emin)5325+ // overflow (or underflow to 0) is guaranteed -- so this case can5326+ // be handled by simply forcing the appropriate excess5327+ if (h>8) { // overflow/underflow5328+ // set up here so Power call below will over or underflow to5329+ // zero; set accumulator to either 2 or 0.025330+ // [stack buffer for a is always big enough for this]5331+ decNumberZero(a);5332+ *a->lsu=2; // not 1 but < exp(1)5333+ if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.025334+ h=8; // clamp so 10**h computable5335+ p=9; // set a working precision5336+ }5337+ else { // h<=85338+ Int maxlever=(rhs->digits>8?1:0);5339+ // [could/should increase this for precisions >40 or so, too]5340+5341+ // if h is 8, cannot normalize to a lower upper limit because5342+ // the final result will not be computable (see notes above),5343+ // but leverage can be applied whenever h is less than 8.5344+ // Apply as much as possible, up to a MAXLEVER digits, which5345+ // sets the tradeoff against the cost of the later a**(10**h).5346+ // As h is increased, the working precision below also5347+ // increases to compensate for the "constant digits at the5348+ // front" effect.5349+ Int lever=MINI(8-h, maxlever); // leverage attainable5350+ Int use=-rhs->digits-lever; // exponent to use for RHS5351+ h+=lever; // apply leverage selected5352+ if (h<0) { // clamp5353+ use+=h; // [may end up subnormal]5354+ h=0;5355+ }5356+ // Take a copy of RHS if it needs normalization (true whenever x>=1)5357+ if (rhs->exponent!=use) {5358+ decNumber *newrhs=bufr; // assume will fit on stack5359+ needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);5360+ if (needbytes>sizeof(bufr)) { // need malloc space5361+ allocrhs=(decNumber *)malloc(needbytes);5362+ if (allocrhs==NULL) { // hopeless -- abandon5363+ *status|=DEC_Insufficient_storage;5364+ break;}5365+ newrhs=allocrhs; // use the allocated space5366+ }5367+ decNumberCopy(newrhs, rhs); // copy to safe space5368+ newrhs->exponent=use; // normalize; now <15369+ x=newrhs; // ready for use5370+ // decNumberShow(x);5371+ }5372+5373+ // Now use the usual power series to evaluate exp(x). The5374+ // series starts as 1 + x + x^2/2 ... so prime ready for the5375+ // third term by setting the term variable t=x, the accumulator5376+ // a=1, and the divisor d=2.5377+5378+ // First determine the working precision. From Hull & Abrham5379+ // this is set->digits+h+2. However, if x is 'over-precise' we5380+ // need to allow for all its digits to potentially participate5381+ // (consider an x where all the excess digits are 9s) so in5382+ // this case use x->digits+h+25383+ p=MAXI(x->digits, set->digits)+h+2; // [h<=8]5384+5385+ // a and t are variable precision, and depend on p, so space5386+ // must be allocated for them if necessary5387+5388+ // the accumulator needs to be able to hold 2p digits so that5389+ // the additions on the second and subsequent iterations are5390+ // sufficiently exact.5391+ needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);5392+ if (needbytes>sizeof(bufa)) { // need malloc space5393+ allocbufa=(decNumber *)malloc(needbytes);5394+ if (allocbufa==NULL) { // hopeless -- abandon5395+ *status|=DEC_Insufficient_storage;5396+ break;}5397+ a=allocbufa; // use the allocated space5398+ }5399+ // the term needs to be able to hold p digits (which is5400+ // guaranteed to be larger than x->digits, so the initial copy5401+ // is safe); it may also be used for the raise-to-power5402+ // calculation below, which needs an extra two digits5403+ needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);5404+ if (needbytes>sizeof(buft)) { // need malloc space5405+ allocbuft=(decNumber *)malloc(needbytes);5406+ if (allocbuft==NULL) { // hopeless -- abandon5407+ *status|=DEC_Insufficient_storage;5408+ break;}5409+ t=allocbuft; // use the allocated space5410+ }5411+5412+ decNumberCopy(t, x); // term=x5413+ decNumberZero(a); *a->lsu=1; // accumulator=15414+ decNumberZero(d); *d->lsu=2; // divisor=25415+ decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment5416+5417+ // set up the contexts for calculating a, t, and d5418+ decContextDefault(&tset, DEC_INIT_DECIMAL64);5419+ dset=tset;5420+ // accumulator bounds are set above, set precision now5421+ aset.digits=p*2; // double5422+ // term bounds avoid any underflow or overflow5423+ tset.digits=p;5424+ tset.emin=DEC_MIN_EMIN; // [emax is plenty]5425+ // [dset.digits=16, etc., are sufficient]5426+5427+ // finally ready to roll5428+ for (;;) {5429+ #if DECCHECK5430+ iterations++;5431+ #endif5432+ // only the status from the accumulation is interesting5433+ // [but it should remain unchanged after first add]5434+ decAddOp(a, a, t, &aset, 0, status); // a=a+t5435+ decMultiplyOp(t, t, x, &tset, &ignore); // t=t*x5436+ decDivideOp(t, t, d, &tset, DIVIDE, &ignore); // t=t/d5437+ // the iteration ends when the term cannot affect the result,5438+ // if rounded to p digits, which is when its value is smaller5439+ // than the accumulator by p+1 digits. There must also be5440+ // full precision in a.5441+ if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))5442+ && (a->digits>=p)) break;5443+ decAddOp(d, d, &numone, &dset, 0, &ignore); // d=d+15444+ } // iterate5445+5446+ #if DECCHECK5447+ // just a sanity check; comment out test to show always5448+ if (iterations>p+3)5449+ printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",5450+ (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);5451+ #endif5452+ } // h<=85453+5454+ // apply postconditioning: a=a**(10**h) -- this is calculated5455+ // at a slightly higher precision than Hull & Abrham suggest5456+ if (h>0) {5457+ Int seenbit=0; // set once a 1-bit is seen5458+ Int i; // counter5459+ Int n=powers[h]; // always positive5460+ aset.digits=p+2; // sufficient precision5461+ // avoid the overhead and many extra digits of decNumberPower5462+ // as all that is needed is the short 'multipliers' loop; here5463+ // accumulate the answer into t5464+ decNumberZero(t); *t->lsu=1; // acc=15465+ for (i=1;;i++){ // for each bit [top bit ignored]5466+ // abandon if have had overflow or terminal underflow5467+ if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?5468+ if (*status&DEC_Overflow || ISZERO(t)) break;}5469+ n=n<<1; // move next bit to testable position5470+ if (n<0) { // top bit is set5471+ seenbit=1; // OK, have a significant bit5472+ decMultiplyOp(t, t, a, &aset, status); // acc=acc*x5473+ }5474+ if (i==31) break; // that was the last bit5475+ if (!seenbit) continue; // no need to square 15476+ decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]5477+ } /*i*/ // 32 bits5478+ // decNumberShow(t);5479+ a=t; // and carry on using t instead of a5480+ }5481+5482+ // Copy and round the result to res5483+ residue=1; // indicate dirt to right ..5484+ if (ISZERO(a)) residue=0; // .. unless underflowed to 05485+ aset.digits=set->digits; // [use default rounding]5486+ decCopyFit(res, a, &aset, &residue, status); // copy & shorten5487+ decFinish(res, set, &residue, status); // cleanup/set flags5488+ } while(0); // end protected5489+5490+ if (allocrhs !=NULL) free(allocrhs); // drop any storage used5491+ if (allocbufa!=NULL) free(allocbufa); // ..5492+ if (allocbuft!=NULL) free(allocbuft); // ..5493+ // [status is handled by caller]5494+ return res;5495+ } // decExpOp5496+5497+/* ------------------------------------------------------------------ */5498+/* Initial-estimate natural logarithm table */5499+/* */5500+/* LNnn -- 90-entry 16-bit table for values from .10 through .99. */5501+/* The result is a 4-digit encode of the coefficient (c=the */5502+/* top 14 bits encoding 0-9999) and a 2-digit encode of the */5503+/* exponent (e=the bottom 2 bits encoding 0-3) */5504+/* */5505+/* The resulting value is given by: */5506+/* */5507+/* v = -c * 10**(-e-3) */5508+/* */5509+/* where e and c are extracted from entry k = LNnn[x-10] */5510+/* where x is truncated (NB) into the range 10 through 99, */5511+/* and then c = k>>2 and e = k&3. */5512+/* ------------------------------------------------------------------ */5513+const uShort LNnn[90]={9016, 8652, 8316, 8008, 7724, 7456, 7208,5514+ 6972, 6748, 6540, 6340, 6148, 5968, 5792, 5628, 5464, 5312,5515+ 5164, 5020, 4884, 4748, 4620, 4496, 4376, 4256, 4144, 4032,5516+ 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,5517+ 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,5518+ 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,5519+ 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,5520+ 10197, 9685, 9177, 8677, 8185, 7697, 7213, 6737, 6269, 5801,5521+ 5341, 4889, 4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,5522+ 10130, 6046, 20055};5523+5524+/* ------------------------------------------------------------------ */5525+/* decLnOp -- effect natural logarithm */5526+/* */5527+/* This computes C = ln(A) */5528+/* */5529+/* res is C, the result. C may be A */5530+/* rhs is A */5531+/* set is the context; note that rounding mode has no effect */5532+/* */5533+/* C must have space for set->digits digits. */5534+/* */5535+/* Notable cases: */5536+/* A<0 -> Invalid */5537+/* A=0 -> -Infinity (Exact) */5538+/* A=+Infinity -> +Infinity (Exact) */5539+/* A=1 exactly -> 0 (Exact) */5540+/* */5541+/* Restrictions (as for Exp): */5542+/* */5543+/* digits, emax, and -emin in the context must be less than */5544+/* DEC_MAX_MATH+11 (1000010), and the rhs must be within these */5545+/* bounds or a zero. This is an internal routine, so these */5546+/* restrictions are contractual and not enforced. */5547+/* */5548+/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will */5549+/* almost always be correctly rounded, but may be up to 1 ulp in */5550+/* error in rare cases. */5551+/* ------------------------------------------------------------------ */5552+/* The result is calculated using Newton's method, with each */5553+/* iteration calculating a' = a + x * exp(-a) - 1. See, for example, */5554+/* Epperson 1989. */5555+/* */5556+/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */5557+/* This has to be calculated at the sum of the precision of x and the */5558+/* working precision. */5559+/* */5560+/* Implementation notes: */5561+/* */5562+/* 1. This is separated out as decLnOp so it can be called from */5563+/* other Mathematical functions (e.g., Log 10) with a wider range */5564+/* than normal. In particular, it can handle the slightly wider */5565+/* (+9+2) range needed by a power function. */5566+/* */5567+/* 2. The speed of this function is about 10x slower than exp, as */5568+/* it typically needs 4-6 iterations for short numbers, and the */5569+/* extra precision needed adds a squaring effect, twice. */5570+/* */5571+/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40, */5572+/* as these are common requests. ln(10) is used by log10(x). */5573+/* */5574+/* 4. An iteration might be saved by widening the LNnn table, and */5575+/* would certainly save at least one if it were made ten times */5576+/* bigger, too (for truncated fractions 0.100 through 0.999). */5577+/* However, for most practical evaluations, at least four or five */5578+/* iterations will be neede -- so this would only speed up by */5579+/* 20-25% and that probably does not justify increasing the table */5580+/* size. */5581+/* */5582+/* 5. The static buffers are larger than might be expected to allow */5583+/* for calls from decNumberPower. */5584+/* ------------------------------------------------------------------ */5585+decNumber * decLnOp(decNumber *res, const decNumber *rhs,5586+ decContext *set, uInt *status) {5587+ uInt ignore=0; // working status accumulator5588+ uInt needbytes; // for space calculations5589+ Int residue; // rounding residue5590+ Int r; // rhs=f*10**r [see below]5591+ Int p; // working precision5592+ Int pp; // precision for iteration5593+ Int t; // work5594+5595+ // buffers for a (accumulator, typically precision+2) and b5596+ // (adjustment calculator, same size)5597+ decNumber bufa[D2N(DECBUFFER+12)];5598+ decNumber *allocbufa=NULL; // -> allocated bufa, iff allocated5599+ decNumber *a=bufa; // accumulator/work5600+ decNumber bufb[D2N(DECBUFFER*2+2)];5601+ decNumber *allocbufb=NULL; // -> allocated bufa, iff allocated5602+ decNumber *b=bufb; // adjustment/work5603+5604+ decNumber numone; // constant 15605+ decNumber cmp; // work5606+ decContext aset, bset; // working contexts5607+5608+ #if DECCHECK5609+ Int iterations=0; // for later sanity check5610+ if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;5611+ #endif5612+5613+ do { // protect allocated storage5614+ if (SPECIALARG) { // handle infinities and NaNs5615+ if (decNumberIsInfinite(rhs)) { // an infinity5616+ if (decNumberIsNegative(rhs)) // -Infinity -> error5617+ *status|=DEC_Invalid_operation;5618+ else decNumberCopy(res, rhs); // +Infinity -> self5619+ }5620+ else decNaNs(res, rhs, NULL, set, status); // a NaN5621+ break;}5622+5623+ if (ISZERO(rhs)) { // +/- zeros -> -Infinity5624+ decNumberZero(res); // make clean5625+ res->bits=DECINF|DECNEG; // set - infinity5626+ break;} // [no status to set]5627+5628+ // Non-zero negatives are bad...5629+ if (decNumberIsNegative(rhs)) { // -x -> error5630+ *status|=DEC_Invalid_operation;5631+ break;}5632+5633+ // Here, rhs is positive, finite, and in range5634+5635+ // lookaside fastpath code for ln(2) and ln(10) at common lengths5636+ if (rhs->exponent==0 && set->digits<=40) {5637+ #if DECDPUN==15638+ if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)5639+ #else5640+ if (rhs->lsu[0]==10 && rhs->digits==2) { // ln(10)5641+ #endif5642+ aset=*set; aset.round=DEC_ROUND_HALF_EVEN;5643+ #define LN10 "2.302585092994045684017991454684364207601"5644+ decNumberFromString(res, LN10, &aset);5645+ *status|=(DEC_Inexact | DEC_Rounded); // is inexact5646+ break;}5647+ if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)5648+ aset=*set; aset.round=DEC_ROUND_HALF_EVEN;5649+ #define LN2 "0.6931471805599453094172321214581765680755"5650+ decNumberFromString(res, LN2, &aset);5651+ *status|=(DEC_Inexact | DEC_Rounded);5652+ break;}5653+ } // integer and short5654+5655+ // Determine the working precision. This is normally the5656+ // requested precision + 2, with a minimum of 9. However, if5657+ // the rhs is 'over-precise' then allow for all its digits to5658+ // potentially participate (consider an rhs where all the excess5659+ // digits are 9s) so in this case use rhs->digits+2.5660+ p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;5661+5662+ // Allocate space for the accumulator and the high-precision5663+ // adjustment calculator, if necessary. The accumulator must5664+ // be able to hold p digits, and the adjustment up to5665+ // rhs->digits+p digits. They are also made big enough for 165666+ // digits so that they can be used for calculating the initial5667+ // estimate.5668+ needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);5669+ if (needbytes>sizeof(bufa)) { // need malloc space5670+ allocbufa=(decNumber *)malloc(needbytes);5671+ if (allocbufa==NULL) { // hopeless -- abandon5672+ *status|=DEC_Insufficient_storage;5673+ break;}5674+ a=allocbufa; // use the allocated space5675+ }5676+ pp=p+rhs->digits;5677+ needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);5678+ if (needbytes>sizeof(bufb)) { // need malloc space5679+ allocbufb=(decNumber *)malloc(needbytes);5680+ if (allocbufb==NULL) { // hopeless -- abandon5681+ *status|=DEC_Insufficient_storage;5682+ break;}5683+ b=allocbufb; // use the allocated space5684+ }5685+5686+ // Prepare an initial estimate in acc. Calculate this by5687+ // considering the coefficient of x to be a normalized fraction,5688+ // f, with the decimal point at far left and multiplied by5689+ // 10**r. Then, rhs=f*10**r and 0.1<=f<1, and5690+ // ln(x) = ln(f) + ln(10)*r5691+ // Get the initial estimate for ln(f) from a small lookup5692+ // table (see above) indexed by the first two digits of f,5693+ // truncated.5694+5695+ decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended5696+ r=rhs->exponent+rhs->digits; // 'normalised' exponent5697+ decNumberFromInt32(a, r); // a=r5698+ decNumberFromInt32(b, 2302585); // b=ln(10) (2.302585)5699+ b->exponent=-6; // ..5700+ decMultiplyOp(a, a, b, &aset, &ignore); // a=a*b5701+ // now get top two digits of rhs into b by simple truncate and5702+ // force to integer5703+ residue=0; // (no residue)5704+ aset.digits=2; aset.round=DEC_ROUND_DOWN;5705+ decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten5706+ b->exponent=0; // make integer5707+ t=decGetInt(b); // [cannot fail]5708+ if (t<10) t=X10(t); // adjust single-digit b5709+ t=LNnn[t-10]; // look up ln(b)5710+ decNumberFromInt32(b, t>>2); // b=ln(b) coefficient5711+ b->exponent=-(t&3)-3; // set exponent5712+ b->bits=DECNEG; // ln(0.10)->ln(0.99) always -ve5713+ aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore5714+ decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b5715+ // the initial estimate is now in a, with up to 4 digits correct.5716+ // When rhs is at or near Nmax the estimate will be low, so we5717+ // will approach it from below, avoiding overflow when calling exp.5718+5719+ decNumberZero(&numone); *numone.lsu=1; // constant 1 for adjustment5720+5721+ // accumulator bounds are as requested (could underflow, but5722+ // cannot overflow)5723+ aset.emax=set->emax;5724+ aset.emin=set->emin;5725+ aset.clamp=0; // no concrete format5726+ // set up a context to be used for the multiply and subtract5727+ bset=aset;5728+ bset.emax=DEC_MAX_MATH*2; // use double bounds for the5729+ bset.emin=-DEC_MAX_MATH*2; // adjustment calculation5730+ // [see decExpOp call below]5731+ // for each iteration double the number of digits to calculate,5732+ // up to a maximum of p5733+ pp=9; // initial precision5734+ // [initially 9 as then the sequence starts 7+2, 16+2, and5735+ // 34+2, which is ideal for standard-sized numbers]5736+ aset.digits=pp; // working context5737+ bset.digits=pp+rhs->digits; // wider context5738+ for (;;) { // iterate5739+ #if DECCHECK5740+ iterations++;5741+ if (iterations>24) break; // consider 9 * 2**245742+ #endif5743+ // calculate the adjustment (exp(-a)*x-1) into b. This is a5744+ // catastrophic subtraction but it really is the difference5745+ // from 1 that is of interest.5746+ // Use the internal entry point to Exp as it allows the double5747+ // range for calculating exp(-a) when a is the tiniest subnormal.5748+ a->bits^=DECNEG; // make -a5749+ decExpOp(b, a, &bset, &ignore); // b=exp(-a)5750+ a->bits^=DECNEG; // restore sign of a5751+ // now multiply by rhs and subtract 1, at the wider precision5752+ decMultiplyOp(b, b, rhs, &bset, &ignore); // b=b*rhs5753+ decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-15754+5755+ // the iteration ends when the adjustment cannot affect the5756+ // result by >=0.5 ulp (at the requested digits), which5757+ // is when its value is smaller than the accumulator by5758+ // set->digits+1 digits (or it is zero) -- this is a looser5759+ // requirement than for Exp because all that happens to the5760+ // accumulator after this is the final rounding (but note that5761+ // there must also be full precision in a, or a=0).5762+5763+ if (decNumberIsZero(b) ||5764+ (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {5765+ if (a->digits==p) break;5766+ if (decNumberIsZero(a)) {5767+ decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?5768+ if (cmp.lsu[0]==0) a->exponent=0; // yes, exact 05769+ else *status|=(DEC_Inexact | DEC_Rounded); // no, inexact5770+ break;5771+ }5772+ // force padding if adjustment has gone to 0 before full length5773+ if (decNumberIsZero(b)) b->exponent=a->exponent-p;5774+ }5775+5776+ // not done yet ...5777+ decAddOp(a, a, b, &aset, 0, &ignore); // a=a+b for next estimate5778+ if (pp==p) continue; // precision is at maximum5779+ // lengthen the next calculation5780+ pp=pp*2; // double precision5781+ if (pp>p) pp=p; // clamp to maximum5782+ aset.digits=pp; // working context5783+ bset.digits=pp+rhs->digits; // wider context5784+ } // Newton's iteration5785+5786+ #if DECCHECK5787+ // just a sanity check; remove the test to show always5788+ if (iterations>24)5789+ printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",5790+ (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);5791+ #endif5792+5793+ // Copy and round the result to res5794+ residue=1; // indicate dirt to right5795+ if (ISZERO(a)) residue=0; // .. unless underflowed to 05796+ aset.digits=set->digits; // [use default rounding]5797+ decCopyFit(res, a, &aset, &residue, status); // copy & shorten5798+ decFinish(res, set, &residue, status); // cleanup/set flags5799+ } while(0); // end protected5800+5801+ if (allocbufa!=NULL) free(allocbufa); // drop any storage used5802+ if (allocbufb!=NULL) free(allocbufb); // ..5803+ // [status is handled by caller]5804+ return res;5805+ } // decLnOp5806+5807+/* ------------------------------------------------------------------ */5808+/* decQuantizeOp -- force exponent to requested value */5809+/* */5810+/* This computes C = op(A, B), where op adjusts the coefficient */5811+/* of C (by rounding or shifting) such that the exponent (-scale) */5812+/* of C has the value B or matches the exponent of B. */5813+/* The numerical value of C will equal A, except for the effects of */5814+/* any rounding that occurred. */5815+/* */5816+/* res is C, the result. C may be A or B */5817+/* lhs is A, the number to adjust */5818+/* rhs is B, the requested exponent */5819+/* set is the context */5820+/* quant is 1 for quantize or 0 for rescale */5821+/* status is the status accumulator (this can be called without */5822+/* risk of control loss) */5823+/* */5824+/* C must have space for set->digits digits. */5825+/* */5826+/* Unless there is an error or the result is infinite, the exponent */5827+/* after the operation is guaranteed to be that requested. */5828+/* ------------------------------------------------------------------ */5829+static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,5830+ const decNumber *rhs, decContext *set,5831+ Flag quant, uInt *status) {5832+ #if DECSUBSET5833+ decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated5834+ decNumber *allocrhs=NULL; // .., rhs5835+ #endif5836+ const decNumber *inrhs=rhs; // save original rhs5837+ Int reqdigits=set->digits; // requested DIGITS5838+ Int reqexp; // requested exponent [-scale]5839+ Int residue=0; // rounding residue5840+ Int etiny=set->emin-(reqdigits-1);5841+5842+ #if DECCHECK5843+ if (decCheckOperands(res, lhs, rhs, set)) return res;5844+ #endif5845+5846+ do { // protect allocated storage5847+ #if DECSUBSET5848+ if (!set->extended) {5849+ // reduce operands and set lostDigits status, as needed5850+ if (lhs->digits>reqdigits) {5851+ alloclhs=decRoundOperand(lhs, set, status);5852+ if (alloclhs==NULL) break;5853+ lhs=alloclhs;5854+ }5855+ if (rhs->digits>reqdigits) { // [this only checks lostDigits]5856+ allocrhs=decRoundOperand(rhs, set, status);5857+ if (allocrhs==NULL) break;5858+ rhs=allocrhs;5859+ }5860+ }5861+ #endif5862+ // [following code does not require input rounding]5863+5864+ // Handle special values5865+ if (SPECIALARGS) {5866+ // NaNs get usual processing5867+ if (SPECIALARGS & (DECSNAN | DECNAN))5868+ decNaNs(res, lhs, rhs, set, status);5869+ // one infinity but not both is bad5870+ else if ((lhs->bits ^ rhs->bits) & DECINF)5871+ *status|=DEC_Invalid_operation;5872+ // both infinity: return lhs5873+ else decNumberCopy(res, lhs); // [nop if in place]5874+ break;5875+ }5876+5877+ // set requested exponent5878+ if (quant) reqexp=inrhs->exponent; // quantize -- match exponents5879+ else { // rescale -- use value of rhs5880+ // Original rhs must be an integer that fits and is in range,5881+ // which could be from -1999999997 to +999999999, thanks to5882+ // subnormals5883+ reqexp=decGetInt(inrhs); // [cannot fail]5884+ }5885+5886+ #if DECSUBSET5887+ if (!set->extended) etiny=set->emin; // no subnormals5888+ #endif5889+5890+ if (reqexp==BADINT // bad (rescale only) or ..5891+ || reqexp==BIGODD || reqexp==BIGEVEN // very big (ditto) or ..5892+ || (reqexp<etiny) // < lowest5893+ || (reqexp>set->emax)) { // > emax5894+ *status|=DEC_Invalid_operation;5895+ break;}5896+5897+ // the RHS has been processed, so it can be overwritten now if necessary5898+ if (ISZERO(lhs)) { // zero coefficient unchanged5899+ decNumberCopy(res, lhs); // [nop if in place]5900+ res->exponent=reqexp; // .. just set exponent5901+ #if DECSUBSET5902+ if (!set->extended) res->bits=0; // subset specification; no -05903+ #endif5904+ }5905+ else { // non-zero lhs5906+ Int adjust=reqexp-lhs->exponent; // digit adjustment needed5907+ // if adjusted coefficient will definitely not fit, give up now5908+ if ((lhs->digits-adjust)>reqdigits) {5909+ *status|=DEC_Invalid_operation;5910+ break;5911+ }5912+5913+ if (adjust>0) { // increasing exponent5914+ // this will decrease the length of the coefficient by adjust5915+ // digits, and must round as it does so5916+ decContext workset; // work5917+ workset=*set; // clone rounding, etc.5918+ workset.digits=lhs->digits-adjust; // set requested length5919+ // [note that the latter can be <1, here]5920+ decCopyFit(res, lhs, &workset, &residue, status); // fit to result5921+ decApplyRound(res, &workset, residue, status); // .. and round5922+ residue=0; // [used]5923+ // If just rounded a 999s case, exponent will be off by one;5924+ // adjust back (after checking space), if so.5925+ if (res->exponent>reqexp) {5926+ // re-check needed, e.g., for quantize(0.9999, 0.001) under5927+ // set->digits==35928+ if (res->digits==reqdigits) { // cannot shift by 15929+ *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]5930+ *status|=DEC_Invalid_operation;5931+ break;5932+ }5933+ res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift5934+ res->exponent--; // (re)adjust the exponent.5935+ }5936+ #if DECSUBSET5937+ if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -05938+ #endif5939+ } // increase5940+ else /* adjust<=0 */ { // decreasing or = exponent5941+ // this will increase the length of the coefficient by -adjust5942+ // digits, by adding zero or more trailing zeros; this is5943+ // already checked for fit, above5944+ decNumberCopy(res, lhs); // [it will fit]5945+ // if padding needed (adjust<0), add it now...5946+ if (adjust<0) {5947+ res->digits=decShiftToMost(res->lsu, res->digits, -adjust);5948+ res->exponent+=adjust; // adjust the exponent5949+ }5950+ } // decrease5951+ } // non-zero5952+5953+ // Check for overflow [do not use Finalize in this case, as an5954+ // overflow here is a "don't fit" situation]5955+ if (res->exponent>set->emax-res->digits+1) { // too big5956+ *status|=DEC_Invalid_operation;5957+ break;5958+ }5959+ else {5960+ decFinalize(res, set, &residue, status); // set subnormal flags5961+ *status&=~DEC_Underflow; // suppress Underflow [as per 754]5962+ }5963+ } while(0); // end protected5964+5965+ #if DECSUBSET5966+ if (allocrhs!=NULL) free(allocrhs); // drop any storage used5967+ if (alloclhs!=NULL) free(alloclhs); // ..5968+ #endif5969+ return res;5970+ } // decQuantizeOp5971+5972+/* ------------------------------------------------------------------ */5973+/* decCompareOp -- compare, min, or max two Numbers */5974+/* */5975+/* This computes C = A ? B and carries out one of four operations: */5976+/* COMPARE -- returns the signum (as a number) giving the */5977+/* result of a comparison unless one or both */5978+/* operands is a NaN (in which case a NaN results) */5979+/* COMPSIG -- as COMPARE except that a quiet NaN raises */5980+/* Invalid operation. */5981+/* COMPMAX -- returns the larger of the operands, using the */5982+/* 754 maxnum operation */5983+/* COMPMAXMAG -- ditto, comparing absolute values */5984+/* COMPMIN -- the 754 minnum operation */5985+/* COMPMINMAG -- ditto, comparing absolute values */5986+/* COMTOTAL -- returns the signum (as a number) giving the */5987+/* result of a comparison using 754 total ordering */5988+/* */5989+/* res is C, the result. C may be A and/or B (e.g., X=X?X) */5990+/* lhs is A */5991+/* rhs is B */5992+/* set is the context */5993+/* op is the operation flag */5994+/* status is the usual accumulator */5995+/* */5996+/* C must have space for one digit for COMPARE or set->digits for */5997+/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG. */5998+/* ------------------------------------------------------------------ */5999+/* The emphasis here is on speed for common cases, and avoiding */6000+/* coefficient comparison if possible. */6001+/* ------------------------------------------------------------------ */6002+decNumber * decCompareOp(decNumber *res, const decNumber *lhs,6003+ const decNumber *rhs, decContext *set,6004+ Flag op, uInt *status) {6005+ #if DECSUBSET6006+ decNumber *alloclhs=NULL; // non-NULL if rounded lhs allocated6007+ decNumber *allocrhs=NULL; // .., rhs6008+ #endif6009+ Int result=0; // default result value6010+ uByte merged; // work6011+6012+ #if DECCHECK6013+ if (decCheckOperands(res, lhs, rhs, set)) return res;6014+ #endif6015+6016+ do { // protect allocated storage6017+ #if DECSUBSET6018+ if (!set->extended) {6019+ // reduce operands and set lostDigits status, as needed6020+ if (lhs->digits>set->digits) {6021+ alloclhs=decRoundOperand(lhs, set, status);6022+ if (alloclhs==NULL) {result=BADINT; break;}6023+ lhs=alloclhs;6024+ }6025+ if (rhs->digits>set->digits) {6026+ allocrhs=decRoundOperand(rhs, set, status);6027+ if (allocrhs==NULL) {result=BADINT; break;}6028+ rhs=allocrhs;6029+ }6030+ }6031+ #endif6032+ // [following code does not require input rounding]6033+6034+ // If total ordering then handle differing signs 'up front'6035+ if (op==COMPTOTAL) { // total ordering6036+ if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {6037+ result=-1;6038+ break;6039+ }6040+ if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {6041+ result=+1;6042+ break;6043+ }6044+ }6045+6046+ // handle NaNs specially; let infinities drop through6047+ // This assumes sNaN (even just one) leads to NaN.6048+ merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);6049+ if (merged) { // a NaN bit set6050+ if (op==COMPARE); // result will be NaN6051+ else if (op==COMPSIG) // treat qNaN as sNaN6052+ *status|=DEC_Invalid_operation | DEC_sNaN;6053+ else if (op==COMPTOTAL) { // total ordering, always finite6054+ // signs are known to be the same; compute the ordering here6055+ // as if the signs are both positive, then invert for negatives6056+ if (!decNumberIsNaN(lhs)) result=-1;6057+ else if (!decNumberIsNaN(rhs)) result=+1;6058+ // here if both NaNs6059+ else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;6060+ else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;6061+ else { // both NaN or both sNaN6062+ // now it just depends on the payload6063+ result=decUnitCompare(lhs->lsu, D2U(lhs->digits),6064+ rhs->lsu, D2U(rhs->digits), 0);6065+ // [Error not possible, as these are 'aligned']6066+ } // both same NaNs6067+ if (decNumberIsNegative(lhs)) result=-result;6068+ break;6069+ } // total order6070+6071+ else if (merged & DECSNAN); // sNaN -> qNaN6072+ else { // here if MIN or MAX and one or two quiet NaNs6073+ // min or max -- 754 rules ignore single NaN6074+ if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {6075+ // just one NaN; force choice to be the non-NaN operand6076+ op=COMPMAX;6077+ if (lhs->bits & DECNAN) result=-1; // pick rhs6078+ else result=+1; // pick lhs6079+ break;6080+ }6081+ } // max or min6082+ op=COMPNAN; // use special path6083+ decNaNs(res, lhs, rhs, set, status); // propagate NaN6084+ break;6085+ }6086+ // have numbers6087+ if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);6088+ else result=decCompare(lhs, rhs, 0); // sign matters6089+ } while(0); // end protected6090+6091+ if (result==BADINT) *status|=DEC_Insufficient_storage; // rare6092+ else {6093+ if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum6094+ if (op==COMPTOTAL && result==0) {6095+ // operands are numerically equal or same NaN (and same sign,6096+ // tested first); if identical, leave result 06097+ if (lhs->exponent!=rhs->exponent) {6098+ if (lhs->exponent<rhs->exponent) result=-1;6099+ else result=+1;6100+ if (decNumberIsNegative(lhs)) result=-result;6101+ } // lexp!=rexp6102+ } // total-order by exponent6103+ decNumberZero(res); // [always a valid result]6104+ if (result!=0) { // must be -1 or +16105+ *res->lsu=1;6106+ if (result<0) res->bits=DECNEG;6107+ }6108+ }6109+ else if (op==COMPNAN); // special, drop through6110+ else { // MAX or MIN, non-NaN result6111+ Int residue=0; // rounding accumulator6112+ // choose the operand for the result6113+ const decNumber *choice;6114+ if (result==0) { // operands are numerically equal6115+ // choose according to sign then exponent (see 754)6116+ uByte slhs=(lhs->bits & DECNEG);6117+ uByte srhs=(rhs->bits & DECNEG);6118+ #if DECSUBSET6119+ if (!set->extended) { // subset: force left-hand6120+ op=COMPMAX;6121+ result=+1;6122+ }6123+ else6124+ #endif6125+ if (slhs!=srhs) { // signs differ6126+ if (slhs) result=-1; // rhs is max6127+ else result=+1; // lhs is max6128+ }6129+ else if (slhs && srhs) { // both negative6130+ if (lhs->exponent<rhs->exponent) result=+1;6131+ else result=-1;6132+ // [if equal, use lhs, technically identical]6133+ }6134+ else { // both positive6135+ if (lhs->exponent>rhs->exponent) result=+1;6136+ else result=-1;6137+ // [ditto]6138+ }6139+ } // numerically equal6140+ // here result will be non-0; reverse if looking for MIN6141+ if (op==COMPMIN || op==COMPMINMAG) result=-result;6142+ choice=(result>0 ? lhs : rhs); // choose6143+ // copy chosen to result, rounding if need be6144+ decCopyFit(res, choice, set, &residue, status);6145+ decFinish(res, set, &residue, status);6146+ }6147+ }6148+ #if DECSUBSET6149+ if (allocrhs!=NULL) free(allocrhs); // free any storage used6150+ if (alloclhs!=NULL) free(alloclhs); // ..6151+ #endif6152+ return res;6153+ } // decCompareOp6154+6155+/* ------------------------------------------------------------------ */6156+/* decCompare -- compare two decNumbers by numerical value */6157+/* */6158+/* This routine compares A ? B without altering them. */6159+/* */6160+/* Arg1 is A, a decNumber which is not a NaN */6161+/* Arg2 is B, a decNumber which is not a NaN */6162+/* Arg3 is 1 for a sign-independent compare, 0 otherwise */6163+/* */6164+/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */6165+/* (the only possible failure is an allocation error) */6166+/* ------------------------------------------------------------------ */6167+static Int decCompare(const decNumber *lhs, const decNumber *rhs,6168+ Flag abs) {6169+ Int result; // result value6170+ Int sigr; // rhs signum6171+ Int compare; // work6172+6173+ result=1; // assume signum(lhs)6174+ if (ISZERO(lhs)) result=0;6175+ if (abs) {6176+ if (ISZERO(rhs)) return result; // LHS wins or both 06177+ // RHS is non-zero6178+ if (result==0) return -1; // LHS is 0; RHS wins6179+ // [here, both non-zero, result=1]6180+ }6181+ else { // signs matter6182+ if (result && decNumberIsNegative(lhs)) result=-1;6183+ sigr=1; // compute signum(rhs)6184+ if (ISZERO(rhs)) sigr=0;6185+ else if (decNumberIsNegative(rhs)) sigr=-1;6186+ if (result > sigr) return +1; // L > R, return 16187+ if (result < sigr) return -1; // L < R, return -16188+ if (result==0) return 0; // both 06189+ }6190+6191+ // signums are the same; both are non-zero6192+ if ((lhs->bits | rhs->bits) & DECINF) { // one or more infinities6193+ if (decNumberIsInfinite(rhs)) {6194+ if (decNumberIsInfinite(lhs)) result=0;// both infinite6195+ else result=-result; // only rhs infinite6196+ }6197+ return result;6198+ }6199+ // must compare the coefficients, allowing for exponents6200+ if (lhs->exponent>rhs->exponent) { // LHS exponent larger6201+ // swap sides, and sign6202+ const decNumber *temp=lhs;6203+ lhs=rhs;6204+ rhs=temp;6205+ result=-result;6206+ }6207+ compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),6208+ rhs->lsu, D2U(rhs->digits),6209+ rhs->exponent-lhs->exponent);6210+ if (compare!=BADINT) compare*=result; // comparison succeeded6211+ return compare;6212+ } // decCompare6213+6214+/* ------------------------------------------------------------------ */6215+/* decUnitCompare -- compare two >=0 integers in Unit arrays */6216+/* */6217+/* This routine compares A ? B*10**E where A and B are unit arrays */6218+/* A is a plain integer */6219+/* B has an exponent of E (which must be non-negative) */6220+/* */6221+/* Arg1 is A first Unit (lsu) */6222+/* Arg2 is A length in Units */6223+/* Arg3 is B first Unit (lsu) */6224+/* Arg4 is B length in Units */6225+/* Arg5 is E (0 if the units are aligned) */6226+/* */6227+/* returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure */6228+/* (the only possible failure is an allocation error, which can */6229+/* only occur if E!=0) */6230+/* ------------------------------------------------------------------ */6231+static Int decUnitCompare(const Unit *a, Int alength,6232+ const Unit *b, Int blength, Int exp) {6233+ Unit *acc; // accumulator for result6234+ Unit accbuff[SD2U(DECBUFFER*2+1)]; // local buffer6235+ Unit *allocacc=NULL; // -> allocated acc buffer, iff allocated6236+ Int accunits, need; // units in use or needed for acc6237+ const Unit *l, *r, *u; // work6238+ Int expunits, exprem, result; // ..6239+6240+ if (exp==0) { // aligned; fastpath6241+ if (alength>blength) return 1;6242+ if (alength<blength) return -1;6243+ // same number of units in both -- need unit-by-unit compare6244+ l=a+alength-1;6245+ r=b+alength-1;6246+ for (;l>=a; l--, r--) {6247+ if (*l>*r) return 1;6248+ if (*l<*r) return -1;6249+ }6250+ return 0; // all units match6251+ } // aligned6252+6253+ // Unaligned. If one is >1 unit longer than the other, padded6254+ // approximately, then can return easily6255+ if (alength>blength+(Int)D2U(exp)) return 1;6256+ if (alength+1<blength+(Int)D2U(exp)) return -1;6257+6258+ // Need to do a real subtract. For this, a result buffer is needed6259+ // even though only the sign is of interest. Its length needs6260+ // to be the larger of alength and padded blength, +26261+ need=blength+D2U(exp); // maximum real length of B6262+ if (need<alength) need=alength;6263+ need+=2;6264+ acc=accbuff; // assume use local buffer6265+ if (need*sizeof(Unit)>sizeof(accbuff)) {6266+ allocacc=(Unit *)malloc(need*sizeof(Unit));6267+ if (allocacc==NULL) return BADINT; // hopeless -- abandon6268+ acc=allocacc;6269+ }6270+ // Calculate units and remainder from exponent.6271+ expunits=exp/DECDPUN;6272+ exprem=exp%DECDPUN;6273+ // subtract [A+B*(-m)]6274+ accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,6275+ -(Int)powers[exprem]);6276+ // [UnitAddSub result may have leading zeros, even on zero]6277+ if (accunits<0) result=-1; // negative result6278+ else { // non-negative result6279+ // check units of the result before freeing any storage6280+ for (u=acc; u<acc+accunits-1 && *u==0;) u++;6281+ result=(*u==0 ? 0 : +1);6282+ }6283+ // clean up and return the result6284+ if (allocacc!=NULL) free(allocacc); // drop any storage used6285+ return result;6286+ } // decUnitCompare6287+6288+/* ------------------------------------------------------------------ */6289+/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays */6290+/* */6291+/* This routine performs the calculation: */6292+/* */6293+/* C=A+(B*M) */6294+/* */6295+/* Where M is in the range -DECDPUNMAX through +DECDPUNMAX. */6296+/* */6297+/* A may be shorter or longer than B. */6298+/* */6299+/* Leading zeros are not removed after a calculation. The result is */6300+/* either the same length as the longer of A and B (adding any */6301+/* shift), or one Unit longer than that (if a Unit carry occurred). */6302+/* */6303+/* A and B content are not altered unless C is also A or B. */6304+/* C may be the same array as A or B, but only if no zero padding is */6305+/* requested (that is, C may be B only if bshift==0). */6306+/* C is filled from the lsu; only those units necessary to complete */6307+/* the calculation are referenced. */6308+/* */6309+/* Arg1 is A first Unit (lsu) */6310+/* Arg2 is A length in Units */6311+/* Arg3 is B first Unit (lsu) */6312+/* Arg4 is B length in Units */6313+/* Arg5 is B shift in Units (>=0; pads with 0 units if positive) */6314+/* Arg6 is C first Unit (lsu) */6315+/* Arg7 is M, the multiplier */6316+/* */6317+/* returns the count of Units written to C, which will be non-zero */6318+/* and negated if the result is negative. That is, the sign of the */6319+/* returned Int is the sign of the result (positive for zero) and */6320+/* the absolute value of the Int is the count of Units. */6321+/* */6322+/* It is the caller's responsibility to make sure that C size is */6323+/* safe, allowing space if necessary for a one-Unit carry. */6324+/* */6325+/* This routine is severely performance-critical; *any* change here */6326+/* must be measured (timed) to assure no performance degradation. */6327+/* In particular, trickery here tends to be counter-productive, as */6328+/* increased complexity of code hurts register optimizations on */6329+/* register-poor architectures. Avoiding divisions is nearly */6330+/* always a Good Idea, however. */6331+/* */6332+/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark */6333+/* (IBM Warwick, UK) for some of the ideas used in this routine. */6334+/* ------------------------------------------------------------------ */6335+static Int decUnitAddSub(const Unit *a, Int alength,6336+ const Unit *b, Int blength, Int bshift,6337+ Unit *c, Int m) {6338+ const Unit *alsu=a; // A lsu [need to remember it]6339+ Unit *clsu=c; // C ditto6340+ Unit *minC; // low water mark for C6341+ Unit *maxC; // high water mark for C6342+ eInt carry=0; // carry integer (could be Long)6343+ Int add; // work6344+ #if DECDPUN<=4 // myriadal, millenary, etc.6345+ Int est; // estimated quotient6346+ #endif6347+6348+ #if DECTRACE6349+ if (alength<1 || blength<1)6350+ printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);6351+ #endif6352+6353+ maxC=c+alength; // A is usually the longer6354+ minC=c+blength; // .. and B the shorter6355+ if (bshift!=0) { // B is shifted; low As copy across6356+ minC+=bshift;6357+ // if in place [common], skip copy unless there's a gap [rare]6358+ if (a==c && bshift<=alength) {6359+ c+=bshift;6360+ a+=bshift;6361+ }6362+ else for (; c<clsu+bshift; a++, c++) { // copy needed6363+ if (a<alsu+alength) *c=*a;6364+ else *c=0;6365+ }6366+ }6367+ if (minC>maxC) { // swap6368+ Unit *hold=minC;6369+ minC=maxC;6370+ maxC=hold;6371+ }6372+6373+ // For speed, do the addition as two loops; the first where both A6374+ // and B contribute, and the second (if necessary) where only one or6375+ // other of the numbers contribute.6376+ // Carry handling is the same (i.e., duplicated) in each case.6377+ for (; c<minC; c++) {6378+ carry+=*a;6379+ a++;6380+ carry+=((eInt)*b)*m; // [special-casing m=1/-16381+ b++; // here is not a win]6382+ // here carry is new Unit of digits; it could be +ve or -ve6383+ if ((ueInt)carry<=DECDPUNMAX) { // fastpath 0-DECDPUNMAX6384+ *c=(Unit)carry;6385+ carry=0;6386+ continue;6387+ }6388+ #if DECDPUN==4 // use divide-by-multiply6389+ if (carry>=0) {6390+ est=(((ueInt)carry>>11)*53687)>>18;6391+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6392+ carry=est; // likely quotient [89%]6393+ if (*c<DECDPUNMAX+1) continue; // estimate was correct6394+ carry++;6395+ *c-=DECDPUNMAX+1;6396+ continue;6397+ }6398+ // negative case6399+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6400+ est=(((ueInt)carry>>11)*53687)>>18;6401+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6402+ carry=est-(DECDPUNMAX+1); // correctly negative6403+ if (*c<DECDPUNMAX+1) continue; // was OK6404+ carry++;6405+ *c-=DECDPUNMAX+1;6406+ #elif DECDPUN==36407+ if (carry>=0) {6408+ est=(((ueInt)carry>>3)*16777)>>21;6409+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6410+ carry=est; // likely quotient [99%]6411+ if (*c<DECDPUNMAX+1) continue; // estimate was correct6412+ carry++;6413+ *c-=DECDPUNMAX+1;6414+ continue;6415+ }6416+ // negative case6417+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6418+ est=(((ueInt)carry>>3)*16777)>>21;6419+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6420+ carry=est-(DECDPUNMAX+1); // correctly negative6421+ if (*c<DECDPUNMAX+1) continue; // was OK6422+ carry++;6423+ *c-=DECDPUNMAX+1;6424+ #elif DECDPUN<=26425+ // Can use QUOT10 as carry <= 4 digits6426+ if (carry>=0) {6427+ est=QUOT10(carry, DECDPUN);6428+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6429+ carry=est; // quotient6430+ continue;6431+ }6432+ // negative case6433+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6434+ est=QUOT10(carry, DECDPUN);6435+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6436+ carry=est-(DECDPUNMAX+1); // correctly negative6437+ #else6438+ // remainder operator is undefined if negative, so must test6439+ if ((ueInt)carry<(DECDPUNMAX+1)*2) { // fastpath carry +16440+ *c=(Unit)(carry-(DECDPUNMAX+1)); // [helps additions]6441+ carry=1;6442+ continue;6443+ }6444+ if (carry>=0) {6445+ *c=(Unit)(carry%(DECDPUNMAX+1));6446+ carry=carry/(DECDPUNMAX+1);6447+ continue;6448+ }6449+ // negative case6450+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6451+ *c=(Unit)(carry%(DECDPUNMAX+1));6452+ carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);6453+ #endif6454+ } // c6455+6456+ // now may have one or other to complete6457+ // [pretest to avoid loop setup/shutdown]6458+ if (c<maxC) for (; c<maxC; c++) {6459+ if (a<alsu+alength) { // still in A6460+ carry+=*a;6461+ a++;6462+ }6463+ else { // inside B6464+ carry+=((eInt)*b)*m;6465+ b++;6466+ }6467+ // here carry is new Unit of digits; it could be +ve or -ve and6468+ // magnitude up to DECDPUNMAX squared6469+ if ((ueInt)carry<=DECDPUNMAX) { // fastpath 0-DECDPUNMAX6470+ *c=(Unit)carry;6471+ carry=0;6472+ continue;6473+ }6474+ // result for this unit is negative or >DECDPUNMAX6475+ #if DECDPUN==4 // use divide-by-multiply6476+ if (carry>=0) {6477+ est=(((ueInt)carry>>11)*53687)>>18;6478+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6479+ carry=est; // likely quotient [79.7%]6480+ if (*c<DECDPUNMAX+1) continue; // estimate was correct6481+ carry++;6482+ *c-=DECDPUNMAX+1;6483+ continue;6484+ }6485+ // negative case6486+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6487+ est=(((ueInt)carry>>11)*53687)>>18;6488+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6489+ carry=est-(DECDPUNMAX+1); // correctly negative6490+ if (*c<DECDPUNMAX+1) continue; // was OK6491+ carry++;6492+ *c-=DECDPUNMAX+1;6493+ #elif DECDPUN==36494+ if (carry>=0) {6495+ est=(((ueInt)carry>>3)*16777)>>21;6496+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6497+ carry=est; // likely quotient [99%]6498+ if (*c<DECDPUNMAX+1) continue; // estimate was correct6499+ carry++;6500+ *c-=DECDPUNMAX+1;6501+ continue;6502+ }6503+ // negative case6504+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6505+ est=(((ueInt)carry>>3)*16777)>>21;6506+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6507+ carry=est-(DECDPUNMAX+1); // correctly negative6508+ if (*c<DECDPUNMAX+1) continue; // was OK6509+ carry++;6510+ *c-=DECDPUNMAX+1;6511+ #elif DECDPUN<=26512+ if (carry>=0) {6513+ est=QUOT10(carry, DECDPUN);6514+ *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder6515+ carry=est; // quotient6516+ continue;6517+ }6518+ // negative case6519+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6520+ est=QUOT10(carry, DECDPUN);6521+ *c=(Unit)(carry-est*(DECDPUNMAX+1));6522+ carry=est-(DECDPUNMAX+1); // correctly negative6523+ #else6524+ if ((ueInt)carry<(DECDPUNMAX+1)*2){ // fastpath carry 16525+ *c=(Unit)(carry-(DECDPUNMAX+1));6526+ carry=1;6527+ continue;6528+ }6529+ // remainder operator is undefined if negative, so must test6530+ if (carry>=0) {6531+ *c=(Unit)(carry%(DECDPUNMAX+1));6532+ carry=carry/(DECDPUNMAX+1);6533+ continue;6534+ }6535+ // negative case6536+ carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive6537+ *c=(Unit)(carry%(DECDPUNMAX+1));6538+ carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);6539+ #endif6540+ } // c6541+6542+ // OK, all A and B processed; might still have carry or borrow6543+ // return number of Units in the result, negated if a borrow6544+ if (carry==0) return c-clsu; // no carry, so no more to do6545+ if (carry>0) { // positive carry6546+ *c=(Unit)carry; // place as new unit6547+ c++; // ..6548+ return c-clsu;6549+ }6550+ // -ve carry: it's a borrow; complement needed6551+ add=1; // temporary carry...6552+ for (c=clsu; c<maxC; c++) {6553+ add=DECDPUNMAX+add-*c;6554+ if (add<=DECDPUNMAX) {6555+ *c=(Unit)add;6556+ add=0;6557+ }6558+ else {6559+ *c=0;6560+ add=1;6561+ }6562+ }6563+ // add an extra unit iff it would be non-zero6564+ #if DECTRACE6565+ printf("UAS borrow: add %ld, carry %ld\n", add, carry);6566+ #endif6567+ if ((add-carry-1)!=0) {6568+ *c=(Unit)(add-carry-1);6569+ c++; // interesting, include it6570+ }6571+ return clsu-c; // -ve result indicates borrowed6572+ } // decUnitAddSub6573+6574+/* ------------------------------------------------------------------ */6575+/* decTrim -- trim trailing zeros or normalize */6576+/* */6577+/* dn is the number to trim or normalize */6578+/* set is the context to use to check for clamp */6579+/* all is 1 to remove all trailing zeros, 0 for just fraction ones */6580+/* noclamp is 1 to unconditional (unclamped) trim */6581+/* dropped returns the number of discarded trailing zeros */6582+/* returns dn */6583+/* */6584+/* If clamp is set in the context then the number of zeros trimmed */6585+/* may be limited if the exponent is high. */6586+/* All fields are updated as required. This is a utility operation, */6587+/* so special values are unchanged and no error is possible. */6588+/* ------------------------------------------------------------------ */6589+static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,6590+ Flag noclamp, Int *dropped) {6591+ Int d, exp; // work6592+ uInt cut; // ..6593+ Unit *up; // -> current Unit6594+6595+ #if DECCHECK6596+ if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;6597+ #endif6598+6599+ *dropped=0; // assume no zeros dropped6600+ if ((dn->bits & DECSPECIAL) // fast exit if special ..6601+ || (*dn->lsu & 0x01)) return dn; // .. or odd6602+ if (ISZERO(dn)) { // .. or 06603+ dn->exponent=0; // (sign is preserved)6604+ return dn;6605+ }6606+6607+ // have a finite number which is even6608+ exp=dn->exponent;6609+ cut=1; // digit (1-DECDPUN) in Unit6610+ up=dn->lsu; // -> current Unit6611+ for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]6612+ // slice by powers6613+ #if DECDPUN<=46614+ uInt quot=QUOT10(*up, cut);6615+ if ((*up-quot*powers[cut])!=0) break; // found non-0 digit6616+ #else6617+ if (*up%powers[cut]!=0) break; // found non-0 digit6618+ #endif6619+ // have a trailing 06620+ if (!all) { // trimming6621+ // [if exp>0 then all trailing 0s are significant for trim]6622+ if (exp<=0) { // if digit might be significant6623+ if (exp==0) break; // then quit6624+ exp++; // next digit might be significant6625+ }6626+ }6627+ cut++; // next power6628+ if (cut>DECDPUN) { // need new Unit6629+ up++;6630+ cut=1;6631+ }6632+ } // d6633+ if (d==0) return dn; // none to drop6634+6635+ // may need to limit drop if clamping6636+ if (set->clamp && !noclamp) {6637+ Int maxd=set->emax-set->digits+1-dn->exponent;6638+ if (maxd<=0) return dn; // nothing possible6639+ if (d>maxd) d=maxd;6640+ }6641+6642+ // effect the drop6643+ decShiftToLeast(dn->lsu, D2U(dn->digits), d);6644+ dn->exponent+=d; // maintain numerical value6645+ dn->digits-=d; // new length6646+ *dropped=d; // report the count6647+ return dn;6648+ } // decTrim6649+6650+/* ------------------------------------------------------------------ */6651+/* decReverse -- reverse a Unit array in place */6652+/* */6653+/* ulo is the start of the array */6654+/* uhi is the end of the array (highest Unit to include) */6655+/* */6656+/* The units ulo through uhi are reversed in place (if the number */6657+/* of units is odd, the middle one is untouched). Note that the */6658+/* digit(s) in each unit are unaffected. */6659+/* ------------------------------------------------------------------ */6660+static void decReverse(Unit *ulo, Unit *uhi) {6661+ Unit temp;6662+ for (; ulo<uhi; ulo++, uhi--) {6663+ temp=*ulo;6664+ *ulo=*uhi;6665+ *uhi=temp;6666+ }6667+ return;6668+ } // decReverse6669+6670+/* ------------------------------------------------------------------ */6671+/* decShiftToMost -- shift digits in array towards most significant */6672+/* */6673+/* uar is the array */6674+/* digits is the count of digits in use in the array */6675+/* shift is the number of zeros to pad with (least significant); */6676+/* it must be zero or positive */6677+/* */6678+/* returns the new length of the integer in the array, in digits */6679+/* */6680+/* No overflow is permitted (that is, the uar array must be known to */6681+/* be large enough to hold the result, after shifting). */6682+/* ------------------------------------------------------------------ */6683+static Int decShiftToMost(Unit *uar, Int digits, Int shift) {6684+ Unit *target, *source, *first; // work6685+ Int cut; // odd 0's to add6686+ uInt next; // work6687+6688+ if (shift==0) return digits; // [fastpath] nothing to do6689+ if ((digits+shift)<=DECDPUN) { // [fastpath] single-unit case6690+ *uar=(Unit)(*uar*powers[shift]);6691+ return digits+shift;6692+ }6693+6694+ next=0; // all paths6695+ source=uar+D2U(digits)-1; // where msu comes from6696+ target=source+D2U(shift); // where upper part of first cut goes6697+ cut=DECDPUN-MSUDIGITS(shift); // where to slice6698+ if (cut==0) { // unit-boundary case6699+ for (; source>=uar; source--, target--) *target=*source;6700+ }6701+ else {6702+ first=uar+D2U(digits+shift)-1; // where msu of source will end up6703+ for (; source>=uar; source--, target--) {6704+ // split the source Unit and accumulate remainder for next6705+ #if DECDPUN<=46706+ uInt quot=QUOT10(*source, cut);6707+ uInt rem=*source-quot*powers[cut];6708+ next+=quot;6709+ #else6710+ uInt rem=*source%powers[cut];6711+ next+=*source/powers[cut];6712+ #endif6713+ if (target<=first) *target=(Unit)next; // write to target iff valid6714+ next=rem*powers[DECDPUN-cut]; // save remainder for next Unit6715+ }6716+ } // shift-move6717+6718+ // propagate any partial unit to one below and clear the rest6719+ for (; target>=uar; target--) {6720+ *target=(Unit)next;6721+ next=0;6722+ }6723+ return digits+shift;6724+ } // decShiftToMost6725+6726+/* ------------------------------------------------------------------ */6727+/* decShiftToLeast -- shift digits in array towards least significant */6728+/* */6729+/* uar is the array */6730+/* units is length of the array, in units */6731+/* shift is the number of digits to remove from the lsu end; it */6732+/* must be zero or positive and <= than units*DECDPUN. */6733+/* */6734+/* returns the new length of the integer in the array, in units */6735+/* */6736+/* Removed digits are discarded (lost). Units not required to hold */6737+/* the final result are unchanged. */6738+/* ------------------------------------------------------------------ */6739+static Int decShiftToLeast(Unit *uar, Int units, Int shift) {6740+ Unit *target, *up; // work6741+ Int cut, count; // work6742+ Int quot, rem; // for division6743+6744+ if (shift==0) return units; // [fastpath] nothing to do6745+ if (shift==units*DECDPUN) { // [fastpath] little to do6746+ *uar=0; // all digits cleared gives zero6747+ return 1; // leaves just the one6748+ }6749+6750+ target=uar; // both paths6751+ cut=MSUDIGITS(shift);6752+ if (cut==DECDPUN) { // unit-boundary case; easy6753+ up=uar+D2U(shift);6754+ for (; up<uar+units; target++, up++) *target=*up;6755+ return target-uar;6756+ }6757+6758+ // messier6759+ up=uar+D2U(shift-cut); // source; correct to whole Units6760+ count=units*DECDPUN-shift; // the maximum new length6761+ #if DECDPUN<=46762+ quot=QUOT10(*up, cut);6763+ #else6764+ quot=*up/powers[cut];6765+ #endif6766+ for (; ; target++) {6767+ *target=(Unit)quot;6768+ count-=(DECDPUN-cut);6769+ if (count<=0) break;6770+ up++;6771+ quot=*up;6772+ #if DECDPUN<=46773+ quot=QUOT10(quot, cut);6774+ rem=*up-quot*powers[cut];6775+ #else6776+ rem=quot%powers[cut];6777+ quot=quot/powers[cut];6778+ #endif6779+ *target=(Unit)(*target+rem*powers[DECDPUN-cut]);6780+ count-=cut;6781+ if (count<=0) break;6782+ }6783+ return target-uar+1;6784+ } // decShiftToLeast6785+6786+#if DECSUBSET6787+/* ------------------------------------------------------------------ */6788+/* decRoundOperand -- round an operand [used for subset only] */6789+/* */6790+/* dn is the number to round (dn->digits is > set->digits) */6791+/* set is the relevant context */6792+/* status is the status accumulator */6793+/* */6794+/* returns an allocated decNumber with the rounded result. */6795+/* */6796+/* lostDigits and other status may be set by this. */6797+/* */6798+/* Since the input is an operand, it must not be modified. */6799+/* Instead, return an allocated decNumber, rounded as required. */6800+/* It is the caller's responsibility to free the allocated storage. */6801+/* */6802+/* If no storage is available then the result cannot be used, so NULL */6803+/* is returned. */6804+/* ------------------------------------------------------------------ */6805+static decNumber *decRoundOperand(const decNumber *dn, decContext *set,6806+ uInt *status) {6807+ decNumber *res; // result structure6808+ uInt newstatus=0; // status from round6809+ Int residue=0; // rounding accumulator6810+6811+ // Allocate storage for the returned decNumber, big enough for the6812+ // length specified by the context6813+ res=(decNumber *)malloc(sizeof(decNumber)6814+ +(D2U(set->digits)-1)*sizeof(Unit));6815+ if (res==NULL) {6816+ *status|=DEC_Insufficient_storage;6817+ return NULL;6818+ }6819+ decCopyFit(res, dn, set, &residue, &newstatus);6820+ decApplyRound(res, set, residue, &newstatus);6821+6822+ // If that set Inexact then "lost digits" is raised...6823+ if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;6824+ *status|=newstatus;6825+ return res;6826+ } // decRoundOperand6827+#endif6828+6829+/* ------------------------------------------------------------------ */6830+/* decCopyFit -- copy a number, truncating the coefficient if needed */6831+/* */6832+/* dest is the target decNumber */6833+/* src is the source decNumber */6834+/* set is the context [used for length (digits) and rounding mode] */6835+/* residue is the residue accumulator */6836+/* status contains the current status to be updated */6837+/* */6838+/* (dest==src is allowed and will be a no-op if fits) */6839+/* All fields are updated as required. */6840+/* ------------------------------------------------------------------ */6841+static void decCopyFit(decNumber *dest, const decNumber *src,6842+ decContext *set, Int *residue, uInt *status) {6843+ dest->bits=src->bits;6844+ dest->exponent=src->exponent;6845+ decSetCoeff(dest, set, src->lsu, src->digits, residue, status);6846+ } // decCopyFit6847+6848+/* ------------------------------------------------------------------ */6849+/* decSetCoeff -- set the coefficient of a number */6850+/* */6851+/* dn is the number whose coefficient array is to be set. */6852+/* It must have space for set->digits digits */6853+/* set is the context [for size] */6854+/* lsu -> lsu of the source coefficient [may be dn->lsu] */6855+/* len is digits in the source coefficient [may be dn->digits] */6856+/* residue is the residue accumulator. This has values as in */6857+/* decApplyRound, and will be unchanged unless the */6858+/* target size is less than len. In this case, the */6859+/* coefficient is truncated and the residue is updated to */6860+/* reflect the previous residue and the dropped digits. */6861+/* status is the status accumulator, as usual */6862+/* */6863+/* The coefficient may already be in the number, or it can be an */6864+/* external intermediate array. If it is in the number, lsu must == */6865+/* dn->lsu and len must == dn->digits. */6866+/* */6867+/* Note that the coefficient length (len) may be < set->digits, and */6868+/* in this case this merely copies the coefficient (or is a no-op */6869+/* if dn->lsu==lsu). */6870+/* */6871+/* Note also that (only internally, from decQuantizeOp and */6872+/* decSetSubnormal) the value of set->digits may be less than one, */6873+/* indicating a round to left. This routine handles that case */6874+/* correctly; caller ensures space. */6875+/* */6876+/* dn->digits, dn->lsu (and as required), and dn->exponent are */6877+/* updated as necessary. dn->bits (sign) is unchanged. */6878+/* */6879+/* DEC_Rounded status is set if any digits are discarded. */6880+/* DEC_Inexact status is set if any non-zero digits are discarded, or */6881+/* incoming residue was non-0 (implies rounded) */6882+/* ------------------------------------------------------------------ */6883+// mapping array: maps 0-9 to canonical residues, so that a residue6884+// can be adjusted in the range [-1, +1] and achieve correct rounding6885+// 0 1 2 3 4 5 6 7 8 96886+static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};6887+static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,6888+ Int len, Int *residue, uInt *status) {6889+ Int discard; // number of digits to discard6890+ uInt cut; // cut point in Unit6891+ const Unit *up; // work6892+ Unit *target; // ..6893+ Int count; // ..6894+ #if DECDPUN<=46895+ uInt temp; // ..6896+ #endif6897+6898+ discard=len-set->digits; // digits to discard6899+ if (discard<=0) { // no digits are being discarded6900+ if (dn->lsu!=lsu) { // copy needed6901+ // copy the coefficient array to the result number; no shift needed6902+ count=len; // avoids D2U6903+ up=lsu;6904+ for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)6905+ *target=*up;6906+ dn->digits=len; // set the new length6907+ }6908+ // dn->exponent and residue are unchanged, record any inexactitude6909+ if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);6910+ return;6911+ }6912+6913+ // some digits must be discarded ...6914+ dn->exponent+=discard; // maintain numerical value6915+ *status|=DEC_Rounded; // accumulate Rounded status6916+ if (*residue>1) *residue=1; // previous residue now to right, so reduce6917+6918+ if (discard>len) { // everything, +1, is being discarded6919+ // guard digit is 06920+ // residue is all the number [NB could be all 0s]6921+ if (*residue<=0) { // not already positive6922+ count=len; // avoids D2U6923+ for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-06924+ *residue=1;6925+ break; // no need to check any others6926+ }6927+ }6928+ if (*residue!=0) *status|=DEC_Inexact; // record inexactitude6929+ *dn->lsu=0; // coefficient will now be 06930+ dn->digits=1; // ..6931+ return;6932+ } // total discard6933+6934+ // partial discard [most common case]6935+ // here, at least the first (most significant) discarded digit exists6936+6937+ // spin up the number, noting residue during the spin, until get to6938+ // the Unit with the first discarded digit. When reach it, extract6939+ // it and remember its position6940+ count=0;6941+ for (up=lsu;; up++) {6942+ count+=DECDPUN;6943+ if (count>=discard) break; // full ones all checked6944+ if (*up!=0) *residue=1;6945+ } // up6946+6947+ // here up -> Unit with first discarded digit6948+ cut=discard-(count-DECDPUN)-1;6949+ if (cut==DECDPUN-1) { // unit-boundary case (fast)6950+ Unit half=(Unit)powers[DECDPUN]>>1;6951+ // set residue directly6952+ if (*up>=half) {6953+ if (*up>half) *residue=7;6954+ else *residue+=5; // add sticky bit6955+ }6956+ else { // <half6957+ if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]6958+ }6959+ if (set->digits<=0) { // special for Quantize/Subnormal :-(6960+ *dn->lsu=0; // .. result is 06961+ dn->digits=1; // ..6962+ }6963+ else { // shift to least6964+ count=set->digits; // now digits to end up with6965+ dn->digits=count; // set the new length6966+ up++; // move to next6967+ // on unit boundary, so shift-down copy loop is simple6968+ for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)6969+ *target=*up;6970+ }6971+ } // unit-boundary case6972+6973+ else { // discard digit is in low digit(s), and not top digit6974+ uInt discard1; // first discarded digit6975+ uInt quot, rem; // for divisions6976+ if (cut==0) quot=*up; // is at bottom of unit6977+ else /* cut>0 */ { // it's not at bottom of unit6978+ #if DECDPUN<=46979+ quot=QUOT10(*up, cut);6980+ rem=*up-quot*powers[cut];6981+ #else6982+ rem=*up%powers[cut];6983+ quot=*up/powers[cut];6984+ #endif6985+ if (rem!=0) *residue=1;6986+ }6987+ // discard digit is now at bottom of quot6988+ #if DECDPUN<=46989+ temp=(quot*6554)>>16; // fast /106990+ // Vowels algorithm here not a win (9 instructions)6991+ discard1=quot-X10(temp);6992+ quot=temp;6993+ #else6994+ discard1=quot%10;6995+ quot=quot/10;6996+ #endif6997+ // here, discard1 is the guard digit, and residue is everything6998+ // else [use mapping array to accumulate residue safely]6999+ *residue+=resmap[discard1];7000+ cut++; // update cut7001+ // here: up -> Unit of the array with bottom digit7002+ // cut is the division point for each Unit7003+ // quot holds the uncut high-order digits for the current unit7004+ if (set->digits<=0) { // special for Quantize/Subnormal :-(7005+ *dn->lsu=0; // .. result is 07006+ dn->digits=1; // ..7007+ }7008+ else { // shift to least needed7009+ count=set->digits; // now digits to end up with7010+ dn->digits=count; // set the new length7011+ // shift-copy the coefficient array to the result number7012+ for (target=dn->lsu; ; target++) {7013+ *target=(Unit)quot;7014+ count-=(DECDPUN-cut);7015+ if (count<=0) break;7016+ up++;7017+ quot=*up;7018+ #if DECDPUN<=47019+ quot=QUOT10(quot, cut);7020+ rem=*up-quot*powers[cut];7021+ #else7022+ rem=quot%powers[cut];7023+ quot=quot/powers[cut];7024+ #endif7025+ *target=(Unit)(*target+rem*powers[DECDPUN-cut]);7026+ count-=cut;7027+ if (count<=0) break;7028+ } // shift-copy loop7029+ } // shift to least7030+ } // not unit boundary7031+7032+ if (*residue!=0) *status|=DEC_Inexact; // record inexactitude7033+ return;7034+ } // decSetCoeff7035+7036+/* ------------------------------------------------------------------ */7037+/* decApplyRound -- apply pending rounding to a number */7038+/* */7039+/* dn is the number, with space for set->digits digits */7040+/* set is the context [for size and rounding mode] */7041+/* residue indicates pending rounding, being any accumulated */7042+/* guard and sticky information. It may be: */7043+/* 6-9: rounding digit is >5 */7044+/* 5: rounding digit is exactly half-way */7045+/* 1-4: rounding digit is <5 and >0 */7046+/* 0: the coefficient is exact */7047+/* -1: as 1, but the hidden digits are subtractive, that */7048+/* is, of the opposite sign to dn. In this case the */7049+/* coefficient must be non-0. This case occurs when */7050+/* subtracting a small number (which can be reduced to */7051+/* a sticky bit); see decAddOp. */7052+/* status is the status accumulator, as usual */7053+/* */7054+/* This routine applies rounding while keeping the length of the */7055+/* coefficient constant. The exponent and status are unchanged */7056+/* except if: */7057+/* */7058+/* -- the coefficient was increased and is all nines (in which */7059+/* case Overflow could occur, and is handled directly here so */7060+/* the caller does not need to re-test for overflow) */7061+/* */7062+/* -- the coefficient was decreased and becomes all nines (in which */7063+/* case Underflow could occur, and is also handled directly). */7064+/* */7065+/* All fields in dn are updated as required. */7066+/* */7067+/* ------------------------------------------------------------------ */7068+static void decApplyRound(decNumber *dn, decContext *set, Int residue,7069+ uInt *status) {7070+ Int bump; // 1 if coefficient needs to be incremented7071+ // -1 if coefficient needs to be decremented7072+7073+ if (residue==0) return; // nothing to apply7074+7075+ bump=0; // assume a smooth ride7076+7077+ // now decide whether, and how, to round, depending on mode7078+ switch (set->round) {7079+ case DEC_ROUND_05UP: { // round zero or five up (for reround)7080+ // This is the same as DEC_ROUND_DOWN unless there is a7081+ // positive residue and the lsd of dn is 0 or 5, in which case7082+ // it is bumped; when residue is <0, the number is therefore7083+ // bumped down unless the final digit was 1 or 6 (in which7084+ // case it is bumped down and then up -- a no-op)7085+ Int lsd5=*dn->lsu%5; // get lsd and quintate7086+ if (residue<0 && lsd5!=1) bump=-1;7087+ else if (residue>0 && lsd5==0) bump=1;7088+ // [bump==1 could be applied directly; use common path for clarity]7089+ break;} // r-057090+7091+ case DEC_ROUND_DOWN: {7092+ // no change, except if negative residue7093+ if (residue<0) bump=-1;7094+ break;} // r-d7095+7096+ case DEC_ROUND_HALF_DOWN: {7097+ if (residue>5) bump=1;7098+ break;} // r-h-d7099+7100+ case DEC_ROUND_HALF_EVEN: {7101+ if (residue>5) bump=1; // >0.5 goes up7102+ else if (residue==5) { // exactly 0.5000...7103+ // 0.5 goes up iff [new] lsd is odd7104+ if (*dn->lsu & 0x01) bump=1;7105+ }7106+ break;} // r-h-e7107+7108+ case DEC_ROUND_HALF_UP: {7109+ if (residue>=5) bump=1;7110+ break;} // r-h-u7111+7112+ case DEC_ROUND_UP: {7113+ if (residue>0) bump=1;7114+ break;} // r-u7115+7116+ case DEC_ROUND_CEILING: {7117+ // same as _UP for positive numbers, and as _DOWN for negatives7118+ // [negative residue cannot occur on 0]7119+ if (decNumberIsNegative(dn)) {7120+ if (residue<0) bump=-1;7121+ }7122+ else {7123+ if (residue>0) bump=1;7124+ }7125+ break;} // r-c7126+7127+ case DEC_ROUND_FLOOR: {7128+ // same as _UP for negative numbers, and as _DOWN for positive7129+ // [negative residue cannot occur on 0]7130+ if (!decNumberIsNegative(dn)) {7131+ if (residue<0) bump=-1;7132+ }7133+ else {7134+ if (residue>0) bump=1;7135+ }7136+ break;} // r-f7137+7138+ default: { // e.g., DEC_ROUND_MAX7139+ *status|=DEC_Invalid_context;7140+ #if DECTRACE || (DECCHECK && DECVERB)7141+ printf("Unknown rounding mode: %d\n", set->round);7142+ #endif7143+ break;}7144+ } // switch7145+7146+ // now bump the number, up or down, if need be7147+ if (bump==0) return; // no action required7148+7149+ // Simply use decUnitAddSub unless bumping up and the number is7150+ // all nines. In this special case set to 100... explicitly7151+ // and adjust the exponent by one (as otherwise could overflow7152+ // the array)7153+ // Similarly handle all-nines result if bumping down.7154+ if (bump>0) {7155+ Unit *up; // work7156+ uInt count=dn->digits; // digits to be checked7157+ for (up=dn->lsu; ; up++) {7158+ if (count<=DECDPUN) {7159+ // this is the last Unit (the msu)7160+ if (*up!=powers[count]-1) break; // not still 9s7161+ // here if it, too, is all nines7162+ *up=(Unit)powers[count-1]; // here 999 -> 100 etc.7163+ for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 07164+ dn->exponent++; // and bump exponent7165+ // [which, very rarely, could cause Overflow...]7166+ if ((dn->exponent+dn->digits)>set->emax+1) {7167+ decSetOverflow(dn, set, status);7168+ }7169+ return; // done7170+ }7171+ // a full unit to check, with more to come7172+ if (*up!=DECDPUNMAX) break; // not still 9s7173+ count-=DECDPUN;7174+ } // up7175+ } // bump>07176+ else { // -17177+ // here checking for a pre-bump of 1000... (leading 1, all7178+ // other digits zero)7179+ Unit *up, *sup; // work7180+ uInt count=dn->digits; // digits to be checked7181+ for (up=dn->lsu; ; up++) {7182+ if (count<=DECDPUN) {7183+ // this is the last Unit (the msu)7184+ if (*up!=powers[count-1]) break; // not 100..7185+ // here if have the 1000... case7186+ sup=up; // save msu pointer7187+ *up=(Unit)powers[count]-1; // here 100 in msu -> 9997188+ // others all to all-nines, too7189+ for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;7190+ dn->exponent--; // and bump exponent7191+7192+ // iff the number was at the subnormal boundary (exponent=etiny)7193+ // then the exponent is now out of range, so it will in fact get7194+ // clamped to etiny and the final 9 dropped.7195+ // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,7196+ // dn->exponent, set->digits);7197+ if (dn->exponent+1==set->emin-set->digits+1) {7198+ if (count==1 && dn->digits==1) *sup=0; // here 9 -> 0[.9]7199+ else {7200+ *sup=(Unit)powers[count-1]-1; // here 999.. in msu -> 99..7201+ dn->digits--;7202+ }7203+ dn->exponent++;7204+ *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;7205+ }7206+ return; // done7207+ }7208+7209+ // a full unit to check, with more to come7210+ if (*up!=0) break; // not still 0s7211+ count-=DECDPUN;7212+ } // up7213+7214+ } // bump<07215+7216+ // Actual bump needed. Do it.7217+ decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);7218+ } // decApplyRound7219+7220+#if DECSUBSET7221+/* ------------------------------------------------------------------ */7222+/* decFinish -- finish processing a number */7223+/* */7224+/* dn is the number */7225+/* set is the context */7226+/* residue is the rounding accumulator (as in decApplyRound) */7227+/* status is the accumulator */7228+/* */7229+/* This finishes off the current number by: */7230+/* 1. If not extended: */7231+/* a. Converting a zero result to clean '0' */7232+/* b. Reducing positive exponents to 0, if would fit in digits */7233+/* 2. Checking for overflow and subnormals (always) */7234+/* Note this is just Finalize when no subset arithmetic. */7235+/* All fields are updated as required. */7236+/* ------------------------------------------------------------------ */7237+static void decFinish(decNumber *dn, decContext *set, Int *residue,7238+ uInt *status) {7239+ if (!set->extended) {7240+ if ISZERO(dn) { // value is zero7241+ dn->exponent=0; // clean exponent ..7242+ dn->bits=0; // .. and sign7243+ return; // no error possible7244+ }7245+ if (dn->exponent>=0) { // non-negative exponent7246+ // >0; reduce to integer if possible7247+ if (set->digits >= (dn->exponent+dn->digits)) {7248+ dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);7249+ dn->exponent=0;7250+ }7251+ }7252+ } // !extended7253+7254+ decFinalize(dn, set, residue, status);7255+ } // decFinish7256+#endif7257+7258+/* ------------------------------------------------------------------ */7259+/* decFinalize -- final check, clamp, and round of a number */7260+/* */7261+/* dn is the number */7262+/* set is the context */7263+/* residue is the rounding accumulator (as in decApplyRound) */7264+/* status is the status accumulator */7265+/* */7266+/* This finishes off the current number by checking for subnormal */7267+/* results, applying any pending rounding, checking for overflow, */7268+/* and applying any clamping. */7269+/* Underflow and overflow conditions are raised as appropriate. */7270+/* All fields are updated as required. */7271+/* ------------------------------------------------------------------ */7272+static void decFinalize(decNumber *dn, decContext *set, Int *residue,7273+ uInt *status) {7274+ Int shift; // shift needed if clamping7275+ Int tinyexp=set->emin-dn->digits+1; // precalculate subnormal boundary7276+7277+ // Must be careful, here, when checking the exponent as the7278+ // adjusted exponent could overflow 31 bits [because it may already7279+ // be up to twice the expected].7280+7281+ // First test for subnormal. This must be done before any final7282+ // round as the result could be rounded to Nmin or 0.7283+ if (dn->exponent<=tinyexp) { // prefilter7284+ Int comp;7285+ decNumber nmin;7286+ // A very nasty case here is dn == Nmin and residue<07287+ if (dn->exponent<tinyexp) {7288+ // Go handle subnormals; this will apply round if needed.7289+ decSetSubnormal(dn, set, residue, status);7290+ return;7291+ }7292+ // Equals case: only subnormal if dn=Nmin and negative residue7293+ decNumberZero(&nmin);7294+ nmin.lsu[0]=1;7295+ nmin.exponent=set->emin;7296+ comp=decCompare(dn, &nmin, 1); // (signless compare)7297+ if (comp==BADINT) { // oops7298+ *status|=DEC_Insufficient_storage; // abandon...7299+ return;7300+ }7301+ if (*residue<0 && comp==0) { // neg residue and dn==Nmin7302+ decApplyRound(dn, set, *residue, status); // might force down7303+ decSetSubnormal(dn, set, residue, status);7304+ return;7305+ }7306+ }7307+7308+ // now apply any pending round (this could raise overflow).7309+ if (*residue!=0) decApplyRound(dn, set, *residue, status);7310+7311+ // Check for overflow [redundant in the 'rare' case] or clamp7312+ if (dn->exponent<=set->emax-set->digits+1) return; // neither needed7313+7314+7315+ // here when might have an overflow or clamp to do7316+ if (dn->exponent>set->emax-dn->digits+1) { // too big7317+ decSetOverflow(dn, set, status);7318+ return;7319+ }7320+ // here when the result is normal but in clamp range7321+ if (!set->clamp) return;7322+7323+ // here when need to apply the IEEE exponent clamp (fold-down)7324+ shift=dn->exponent-(set->emax-set->digits+1);7325+7326+ // shift coefficient (if non-zero)7327+ if (!ISZERO(dn)) {7328+ dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);7329+ }7330+ dn->exponent-=shift; // adjust the exponent to match7331+ *status|=DEC_Clamped; // and record the dirty deed7332+ return;7333+ } // decFinalize7334+7335+/* ------------------------------------------------------------------ */7336+/* decSetOverflow -- set number to proper overflow value */7337+/* */7338+/* dn is the number (used for sign [only] and result) */7339+/* set is the context [used for the rounding mode, etc.] */7340+/* status contains the current status to be updated */7341+/* */7342+/* This sets the sign of a number and sets its value to either */7343+/* Infinity or the maximum finite value, depending on the sign of */7344+/* dn and the rounding mode, following IEEE 754 rules. */7345+/* ------------------------------------------------------------------ */7346+static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {7347+ Flag needmax=0; // result is maximum finite value7348+ uByte sign=dn->bits&DECNEG; // clean and save sign bit7349+7350+ if (ISZERO(dn)) { // zero does not overflow magnitude7351+ Int emax=set->emax; // limit value7352+ if (set->clamp) emax-=set->digits-1; // lower if clamping7353+ if (dn->exponent>emax) { // clamp required7354+ dn->exponent=emax;7355+ *status|=DEC_Clamped;7356+ }7357+ return;7358+ }7359+7360+ decNumberZero(dn);7361+ switch (set->round) {7362+ case DEC_ROUND_DOWN: {7363+ needmax=1; // never Infinity7364+ break;} // r-d7365+ case DEC_ROUND_05UP: {7366+ needmax=1; // never Infinity7367+ break;} // r-057368+ case DEC_ROUND_CEILING: {7369+ if (sign) needmax=1; // Infinity if non-negative7370+ break;} // r-c7371+ case DEC_ROUND_FLOOR: {7372+ if (!sign) needmax=1; // Infinity if negative7373+ break;} // r-f7374+ default: break; // Infinity in all other cases7375+ }7376+ if (needmax) {7377+ decSetMaxValue(dn, set);7378+ dn->bits=sign; // set sign7379+ }7380+ else dn->bits=sign|DECINF; // Value is +/-Infinity7381+ *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;7382+ } // decSetOverflow7383+7384+/* ------------------------------------------------------------------ */7385+/* decSetMaxValue -- set number to +Nmax (maximum normal value) */7386+/* */7387+/* dn is the number to set */7388+/* set is the context [used for digits and emax] */7389+/* */7390+/* This sets the number to the maximum positive value. */7391+/* ------------------------------------------------------------------ */7392+static void decSetMaxValue(decNumber *dn, decContext *set) {7393+ Unit *up; // work7394+ Int count=set->digits; // nines to add7395+ dn->digits=count;7396+ // fill in all nines to set maximum value7397+ for (up=dn->lsu; ; up++) {7398+ if (count>DECDPUN) *up=DECDPUNMAX; // unit full o'nines7399+ else { // this is the msu7400+ *up=(Unit)(powers[count]-1);7401+ break;7402+ }7403+ count-=DECDPUN; // filled those digits7404+ } // up7405+ dn->bits=0; // + sign7406+ dn->exponent=set->emax-set->digits+1;7407+ } // decSetMaxValue7408+7409+/* ------------------------------------------------------------------ */7410+/* decSetSubnormal -- process value whose exponent is <Emin */7411+/* */7412+/* dn is the number (used as input as well as output; it may have */7413+/* an allowed subnormal value, which may need to be rounded) */7414+/* set is the context [used for the rounding mode] */7415+/* residue is any pending residue */7416+/* status contains the current status to be updated */7417+/* */7418+/* If subset mode, set result to zero and set Underflow flags. */7419+/* */7420+/* Value may be zero with a low exponent; this does not set Subnormal */7421+/* but the exponent will be clamped to Etiny. */7422+/* */7423+/* Otherwise ensure exponent is not out of range, and round as */7424+/* necessary. Underflow is set if the result is Inexact. */7425+/* ------------------------------------------------------------------ */7426+static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,7427+ uInt *status) {7428+ decContext workset; // work7429+ Int etiny, adjust; // ..7430+7431+ #if DECSUBSET7432+ // simple set to zero and 'hard underflow' for subset7433+ if (!set->extended) {7434+ decNumberZero(dn);7435+ // always full overflow7436+ *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;7437+ return;7438+ }7439+ #endif7440+7441+ // Full arithmetic -- allow subnormals, rounded to minimum exponent7442+ // (Etiny) if needed7443+ etiny=set->emin-(set->digits-1); // smallest allowed exponent7444+7445+ if ISZERO(dn) { // value is zero7446+ // residue can never be non-zero here7447+ #if DECCHECK7448+ if (*residue!=0) {7449+ printf("++ Subnormal 0 residue %ld\n", (LI)*residue);7450+ *status|=DEC_Invalid_operation;7451+ }7452+ #endif7453+ if (dn->exponent<etiny) { // clamp required7454+ dn->exponent=etiny;7455+ *status|=DEC_Clamped;7456+ }7457+ return;7458+ }7459+7460+ *status|=DEC_Subnormal; // have a non-zero subnormal7461+ adjust=etiny-dn->exponent; // calculate digits to remove7462+ if (adjust<=0) { // not out of range; unrounded7463+ // residue can never be non-zero here, except in the Nmin-residue7464+ // case (which is a subnormal result), so can take fast-path here7465+ // it may already be inexact (from setting the coefficient)7466+ if (*status&DEC_Inexact) *status|=DEC_Underflow;7467+ return;7468+ }7469+7470+ // adjust>0, so need to rescale the result so exponent becomes Etiny7471+ // [this code is similar to that in rescale]7472+ workset=*set; // clone rounding, etc.7473+ workset.digits=dn->digits-adjust; // set requested length7474+ workset.emin-=adjust; // and adjust emin to match7475+ // [note that the latter can be <1, here, similar to Rescale case]7476+ decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);7477+ decApplyRound(dn, &workset, *residue, status);7478+7479+ // Use 754 default rule: Underflow is set iff Inexact7480+ // [independent of whether trapped]7481+ if (*status&DEC_Inexact) *status|=DEC_Underflow;7482+7483+ // if rounded up a 999s case, exponent will be off by one; adjust7484+ // back if so [it will fit, because it was shortened earlier]7485+ if (dn->exponent>etiny) {7486+ dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);7487+ dn->exponent--; // (re)adjust the exponent.7488+ }7489+7490+ // if rounded to zero, it is by definition clamped...7491+ if (ISZERO(dn)) *status|=DEC_Clamped;7492+ } // decSetSubnormal7493+7494+/* ------------------------------------------------------------------ */7495+/* decCheckMath - check entry conditions for a math function */7496+/* */7497+/* This checks the context and the operand */7498+/* */7499+/* rhs is the operand to check */7500+/* set is the context to check */7501+/* status is unchanged if both are good */7502+/* */7503+/* returns non-zero if status is changed, 0 otherwise */7504+/* */7505+/* Restrictions enforced: */7506+/* */7507+/* digits, emax, and -emin in the context must be less than */7508+/* DEC_MAX_MATH (999999), and A must be within these bounds if */7509+/* non-zero. Invalid_operation is set in the status if a */7510+/* restriction is violated. */7511+/* ------------------------------------------------------------------ */7512+static uInt decCheckMath(const decNumber *rhs, decContext *set,7513+ uInt *status) {7514+ uInt save=*status; // record7515+ if (set->digits>DEC_MAX_MATH7516+ || set->emax>DEC_MAX_MATH7517+ || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;7518+ else if ((rhs->digits>DEC_MAX_MATH7519+ || rhs->exponent+rhs->digits>DEC_MAX_MATH+17520+ || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))7521+ && !ISZERO(rhs)) *status|=DEC_Invalid_operation;7522+ return (*status!=save);7523+ } // decCheckMath7524+7525+/* ------------------------------------------------------------------ */7526+/* decGetInt -- get integer from a number */7527+/* */7528+/* dn is the number [which will not be altered] */7529+/* */7530+/* returns one of: */7531+/* BADINT if there is a non-zero fraction */7532+/* the converted integer */7533+/* BIGEVEN if the integer is even and magnitude > 2*10**9 */7534+/* BIGODD if the integer is odd and magnitude > 2*10**9 */7535+/* */7536+/* This checks and gets a whole number from the input decNumber. */7537+/* The sign can be determined from dn by the caller when BIGEVEN or */7538+/* BIGODD is returned. */7539+/* ------------------------------------------------------------------ */7540+static Int decGetInt(const decNumber *dn) {7541+ Int theInt; // result accumulator7542+ const Unit *up; // work7543+ Int got; // digits (real or not) processed7544+ Int ilength=dn->digits+dn->exponent; // integral length7545+ Flag neg=decNumberIsNegative(dn); // 1 if -ve7546+7547+ // The number must be an integer that fits in 10 digits7548+ // Assert, here, that 10 is enough for any rescale Etiny7549+ #if DEC_MAX_EMAX > 9999999997550+ #error GetInt may need updating [for Emax]7551+ #endif7552+ #if DEC_MIN_EMIN < -9999999997553+ #error GetInt may need updating [for Emin]7554+ #endif7555+ if (ISZERO(dn)) return 0; // zeros are OK, with any exponent7556+7557+ up=dn->lsu; // ready for lsu7558+ theInt=0; // ready to accumulate7559+ if (dn->exponent>=0) { // relatively easy7560+ // no fractional part [usual]; allow for positive exponent7561+ got=dn->exponent;7562+ }7563+ else { // -ve exponent; some fractional part to check and discard7564+ Int count=-dn->exponent; // digits to discard7565+ // spin up whole units until reach the Unit with the unit digit7566+ for (; count>=DECDPUN; up++) {7567+ if (*up!=0) return BADINT; // non-zero Unit to discard7568+ count-=DECDPUN;7569+ }7570+ if (count==0) got=0; // [a multiple of DECDPUN]7571+ else { // [not multiple of DECDPUN]7572+ Int rem; // work7573+ // slice off fraction digits and check for non-zero7574+ #if DECDPUN<=47575+ theInt=QUOT10(*up, count);7576+ rem=*up-theInt*powers[count];7577+ #else7578+ rem=*up%powers[count]; // slice off discards7579+ theInt=*up/powers[count];7580+ #endif7581+ if (rem!=0) return BADINT; // non-zero fraction7582+ // it looks good7583+ got=DECDPUN-count; // number of digits so far7584+ up++; // ready for next7585+ }7586+ }7587+ // now it's known there's no fractional part7588+7589+ // tricky code now, to accumulate up to 9.3 digits7590+ if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there7591+7592+ if (ilength<11) {7593+ Int save=theInt;7594+ // collect any remaining unit(s)7595+ for (; got<ilength; up++) {7596+ theInt+=*up*powers[got];7597+ got+=DECDPUN;7598+ }7599+ if (ilength==10) { // need to check for wrap7600+ if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;7601+ // [that test also disallows the BADINT result case]7602+ else if (neg && theInt>1999999997) ilength=11;7603+ else if (!neg && theInt>999999999) ilength=11;7604+ if (ilength==11) theInt=save; // restore correct low bit7605+ }7606+ }7607+7608+ if (ilength>10) { // too big7609+ if (theInt&1) return BIGODD; // bottom bit 17610+ return BIGEVEN; // bottom bit 07611+ }7612+7613+ if (neg) theInt=-theInt; // apply sign7614+ return theInt;7615+ } // decGetInt7616+7617+/* ------------------------------------------------------------------ */7618+/* decDecap -- decapitate the coefficient of a number */7619+/* */7620+/* dn is the number to be decapitated */7621+/* drop is the number of digits to be removed from the left of dn; */7622+/* this must be <= dn->digits (if equal, the coefficient is */7623+/* set to 0) */7624+/* */7625+/* Returns dn; dn->digits will be <= the initial digits less drop */7626+/* (after removing drop digits there may be leading zero digits */7627+/* which will also be removed). Only dn->lsu and dn->digits change. */7628+/* ------------------------------------------------------------------ */7629+static decNumber *decDecap(decNumber *dn, Int drop) {7630+ Unit *msu; // -> target cut point7631+ Int cut; // work7632+ if (drop>=dn->digits) { // losing the whole thing7633+ #if DECCHECK7634+ if (drop>dn->digits)7635+ printf("decDecap called with drop>digits [%ld>%ld]\n",7636+ (LI)drop, (LI)dn->digits);7637+ #endif7638+ dn->lsu[0]=0;7639+ dn->digits=1;7640+ return dn;7641+ }7642+ msu=dn->lsu+D2U(dn->digits-drop)-1; // -> likely msu7643+ cut=MSUDIGITS(dn->digits-drop); // digits to be in use in msu7644+ if (cut!=DECDPUN) *msu%=powers[cut]; // clear left digits7645+ // that may have left leading zero digits, so do a proper count...7646+ dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);7647+ return dn;7648+ } // decDecap7649+7650+/* ------------------------------------------------------------------ */7651+/* decBiStr -- compare string with pairwise options */7652+/* */7653+/* targ is the string to compare */7654+/* str1 is one of the strings to compare against (length may be 0) */7655+/* str2 is the other; it must be the same length as str1 */7656+/* */7657+/* returns 1 if strings compare equal, (that is, it is the same */7658+/* length as str1 and str2, and each character of targ is in either */7659+/* str1 or str2 in the corresponding position), or 0 otherwise */7660+/* */7661+/* This is used for generic caseless compare, including the awkward */7662+/* case of the Turkish dotted and dotless Is. Use as (for example): */7663+/* if (decBiStr(test, "mike", "MIKE")) ... */7664+/* ------------------------------------------------------------------ */7665+static Flag decBiStr(const char *targ, const char *str1, const char *str2) {7666+ for (;;targ++, str1++, str2++) {7667+ if (*targ!=*str1 && *targ!=*str2) return 0;7668+ // *targ has a match in one (or both, if terminator)7669+ if (*targ=='\0') break;7670+ } // forever7671+ return 1;7672+ } // decBiStr7673+7674+/* ------------------------------------------------------------------ */7675+/* decNaNs -- handle NaN operand or operands */7676+/* */7677+/* res is the result number */7678+/* lhs is the first operand */7679+/* rhs is the second operand, or NULL if none */7680+/* context is used to limit payload length */7681+/* status contains the current status */7682+/* returns res in case convenient */7683+/* */7684+/* Called when one or both operands is a NaN, and propagates the */7685+/* appropriate result to res. When an sNaN is found, it is changed */7686+/* to a qNaN and Invalid operation is set. */7687+/* ------------------------------------------------------------------ */7688+static decNumber * decNaNs(decNumber *res, const decNumber *lhs,7689+ const decNumber *rhs, decContext *set,7690+ uInt *status) {7691+ // This decision tree ends up with LHS being the source pointer,7692+ // and status updated if need be7693+ if (lhs->bits & DECSNAN)7694+ *status|=DEC_Invalid_operation | DEC_sNaN;7695+ else if (rhs==NULL);7696+ else if (rhs->bits & DECSNAN) {7697+ lhs=rhs;7698+ *status|=DEC_Invalid_operation | DEC_sNaN;7699+ }7700+ else if (lhs->bits & DECNAN);7701+ else lhs=rhs;7702+7703+ // propagate the payload7704+ if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy7705+ else { // too long7706+ const Unit *ul;7707+ Unit *ur, *uresp1;7708+ // copy safe number of units, then decapitate7709+ res->bits=lhs->bits; // need sign etc.7710+ uresp1=res->lsu+D2U(set->digits);7711+ for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;7712+ res->digits=D2U(set->digits)*DECDPUN;7713+ // maybe still too long7714+ if (res->digits>set->digits) decDecap(res, res->digits-set->digits);7715+ }7716+7717+ res->bits&=~DECSNAN; // convert any sNaN to NaN, while7718+ res->bits|=DECNAN; // .. preserving sign7719+ res->exponent=0; // clean exponent7720+ // [coefficient was copied/decapitated]7721+ return res;7722+ } // decNaNs7723+7724+/* ------------------------------------------------------------------ */7725+/* decStatus -- apply non-zero status */7726+/* */7727+/* dn is the number to set if error */7728+/* status contains the current status (not yet in context) */7729+/* set is the context */7730+/* */7731+/* If the status is an error status, the number is set to a NaN, */7732+/* unless the error was an overflow, divide-by-zero, or underflow, */7733+/* in which case the number will have already been set. */7734+/* */7735+/* The context status is then updated with the new status. Note that */7736+/* this may raise a signal, so control may never return from this */7737+/* routine (hence resources must be recovered before it is called). */7738+/* ------------------------------------------------------------------ */7739+static void decStatus(decNumber *dn, uInt status, decContext *set) {7740+ if (status & DEC_NaNs) { // error status -> NaN7741+ // if cause was an sNaN, clear and propagate [NaN is already set up]7742+ if (status & DEC_sNaN) status&=~DEC_sNaN;7743+ else {7744+ decNumberZero(dn); // other error: clean throughout7745+ dn->bits=DECNAN; // and make a quiet NaN7746+ }7747+ }7748+ decContextSetStatus(set, status); // [may not return]7749+ return;7750+ } // decStatus7751+7752+/* ------------------------------------------------------------------ */7753+/* decGetDigits -- count digits in a Units array */7754+/* */7755+/* uar is the Unit array holding the number (this is often an */7756+/* accumulator of some sort) */7757+/* len is the length of the array in units [>=1] */7758+/* */7759+/* returns the number of (significant) digits in the array */7760+/* */7761+/* All leading zeros are excluded, except the last if the array has */7762+/* only zero Units. */7763+/* ------------------------------------------------------------------ */7764+// This may be called twice during some operations.7765+static Int decGetDigits(Unit *uar, Int len) {7766+ Unit *up=uar+(len-1); // -> msu7767+ Int digits=(len-1)*DECDPUN+1; // possible digits excluding msu7768+ #if DECDPUN>47769+ uInt const *pow; // work7770+ #endif7771+ // (at least 1 in final msu)7772+ #if DECCHECK7773+ if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);7774+ #endif7775+7776+ for (; up>=uar; up--) {7777+ if (*up==0) { // unit is all 0s7778+ if (digits==1) break; // a zero has one digit7779+ digits-=DECDPUN; // adjust for 0 unit7780+ continue;}7781+ // found the first (most significant) non-zero Unit7782+ #if DECDPUN>1 // not done yet7783+ if (*up<10) break; // is 1-97784+ digits++;7785+ #if DECDPUN>2 // not done yet7786+ if (*up<100) break; // is 10-997787+ digits++;7788+ #if DECDPUN>3 // not done yet7789+ if (*up<1000) break; // is 100-9997790+ digits++;7791+ #if DECDPUN>4 // count the rest ...7792+ for (pow=&powers[4]; *up>=*pow; pow++) digits++;7793+ #endif7794+ #endif7795+ #endif7796+ #endif7797+ break;7798+ } // up7799+ return digits;7800+ } // decGetDigits7801+7802+#if DECTRACE | DECCHECK7803+/* ------------------------------------------------------------------ */7804+/* decNumberShow -- display a number [debug aid] */7805+/* dn is the number to show */7806+/* */7807+/* Shows: sign, exponent, coefficient (msu first), digits */7808+/* or: sign, special-value */7809+/* ------------------------------------------------------------------ */7810+// this is public so other modules can use it7811+void decNumberShow(const decNumber *dn) {7812+ const Unit *up; // work7813+ uInt u, d; // ..7814+ Int cut; // ..7815+ char isign='+'; // main sign7816+ if (dn==NULL) {7817+ printf("NULL\n");7818+ return;}7819+ if (decNumberIsNegative(dn)) isign='-';7820+ printf(" >> %c ", isign);7821+ if (dn->bits&DECSPECIAL) { // Is a special value7822+ if (decNumberIsInfinite(dn)) printf("Infinity");7823+ else { // a NaN7824+ if (dn->bits&DECSNAN) printf("sNaN"); // signalling NaN7825+ else printf("NaN");7826+ }7827+ // if coefficient and exponent are 0, no more to do7828+ if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {7829+ printf("\n");7830+ return;}7831+ // drop through to report other information7832+ printf(" ");7833+ }7834+7835+ // now carefully display the coefficient7836+ up=dn->lsu+D2U(dn->digits)-1; // msu7837+ printf("%ld", (LI)*up);7838+ for (up=up-1; up>=dn->lsu; up--) {7839+ u=*up;7840+ printf(":");7841+ for (cut=DECDPUN-1; cut>=0; cut--) {7842+ d=u/powers[cut];7843+ u-=d*powers[cut];7844+ printf("%ld", (LI)d);7845+ } // cut7846+ } // up7847+ if (dn->exponent!=0) {7848+ char esign='+';7849+ if (dn->exponent<0) esign='-';7850+ printf(" E%c%ld", esign, (LI)abs(dn->exponent));7851+ }7852+ printf(" [%ld]\n", (LI)dn->digits);7853+ } // decNumberShow7854+#endif7855+7856+#if DECTRACE || DECCHECK7857+/* ------------------------------------------------------------------ */7858+/* decDumpAr -- display a unit array [debug/check aid] */7859+/* name is a single-character tag name */7860+/* ar is the array to display */7861+/* len is the length of the array in Units */7862+/* ------------------------------------------------------------------ */7863+static void decDumpAr(char name, const Unit *ar, Int len) {7864+ Int i;7865+ const char *spec;7866+ #if DECDPUN==97867+ spec="%09d ";7868+ #elif DECDPUN==87869+ spec="%08d ";7870+ #elif DECDPUN==77871+ spec="%07d ";7872+ #elif DECDPUN==67873+ spec="%06d ";7874+ #elif DECDPUN==57875+ spec="%05d ";7876+ #elif DECDPUN==47877+ spec="%04d ";7878+ #elif DECDPUN==37879+ spec="%03d ";7880+ #elif DECDPUN==27881+ spec="%02d ";7882+ #else7883+ spec="%d ";7884+ #endif7885+ printf(" :%c: ", name);7886+ for (i=len-1; i>=0; i--) {7887+ if (i==len-1) printf("%ld ", (LI)ar[i]);7888+ else printf(spec, ar[i]);7889+ }7890+ printf("\n");7891+ return;}7892+#endif7893+7894+#if DECCHECK7895+/* ------------------------------------------------------------------ */7896+/* decCheckOperands -- check operand(s) to a routine */7897+/* res is the result structure (not checked; it will be set to */7898+/* quiet NaN if error found (and it is not NULL)) */7899+/* lhs is the first operand (may be DECUNRESU) */7900+/* rhs is the second (may be DECUNUSED) */7901+/* set is the context (may be DECUNCONT) */7902+/* returns 0 if both operands, and the context are clean, or 1 */7903+/* otherwise (in which case the context will show an error, */7904+/* unless NULL). Note that res is not cleaned; caller should */7905+/* handle this so res=NULL case is safe. */7906+/* The caller is expected to abandon immediately if 1 is returned. */7907+/* ------------------------------------------------------------------ */7908+static Flag decCheckOperands(decNumber *res, const decNumber *lhs,7909+ const decNumber *rhs, decContext *set) {7910+ Flag bad=0;7911+ if (set==NULL) { // oops; hopeless7912+ #if DECTRACE || DECVERB7913+ printf("Reference to context is NULL.\n");7914+ #endif7915+ bad=1;7916+ return 1;}7917+ else if (set!=DECUNCONT7918+ && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {7919+ bad=1;7920+ #if DECTRACE || DECVERB7921+ printf("Bad context [digits=%ld round=%ld].\n",7922+ (LI)set->digits, (LI)set->round);7923+ #endif7924+ }7925+ else {7926+ if (res==NULL) {7927+ bad=1;7928+ #if DECTRACE7929+ // this one not DECVERB as standard tests include NULL7930+ printf("Reference to result is NULL.\n");7931+ #endif7932+ }7933+ if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));7934+ if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));7935+ }7936+ if (bad) {7937+ if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);7938+ if (res!=DECUNRESU && res!=NULL) {7939+ decNumberZero(res);7940+ res->bits=DECNAN; // qNaN7941+ }7942+ }7943+ return bad;7944+ } // decCheckOperands7945+7946+/* ------------------------------------------------------------------ */7947+/* decCheckNumber -- check a number */7948+/* dn is the number to check */7949+/* returns 0 if the number is clean, or 1 otherwise */7950+/* */7951+/* The number is considered valid if it could be a result from some */7952+/* operation in some valid context. */7953+/* ------------------------------------------------------------------ */7954+static Flag decCheckNumber(const decNumber *dn) {7955+ const Unit *up; // work7956+ uInt maxuint; // ..7957+ Int ae, d, digits; // ..7958+ Int emin, emax; // ..7959+7960+ if (dn==NULL) { // hopeless7961+ #if DECTRACE7962+ // this one not DECVERB as standard tests include NULL7963+ printf("Reference to decNumber is NULL.\n");7964+ #endif7965+ return 1;}7966+7967+ // check special values7968+ if (dn->bits & DECSPECIAL) {7969+ if (dn->exponent!=0) {7970+ #if DECTRACE || DECVERB7971+ printf("Exponent %ld (not 0) for a special value [%02x].\n",7972+ (LI)dn->exponent, dn->bits);7973+ #endif7974+ return 1;}7975+7976+ // 2003.09.08: NaNs may now have coefficients, so next tests Inf only7977+ if (decNumberIsInfinite(dn)) {7978+ if (dn->digits!=1) {7979+ #if DECTRACE || DECVERB7980+ printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);7981+ #endif7982+ return 1;}7983+ if (*dn->lsu!=0) {7984+ #if DECTRACE || DECVERB7985+ printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);7986+ #endif7987+ decDumpAr('I', dn->lsu, D2U(dn->digits));7988+ return 1;}7989+ } // Inf7990+ // 2002.12.26: negative NaNs can now appear through proposed IEEE7991+ // concrete formats (decimal64, etc.).7992+ return 0;7993+ }7994+7995+ // check the coefficient7996+ if (dn->digits<1 || dn->digits>DECNUMMAXP) {7997+ #if DECTRACE || DECVERB7998+ printf("Digits %ld in number.\n", (LI)dn->digits);7999+ #endif8000+ return 1;}8001+8002+ d=dn->digits;8003+8004+ for (up=dn->lsu; d>0; up++) {8005+ if (d>DECDPUN) maxuint=DECDPUNMAX;8006+ else { // reached the msu8007+ maxuint=powers[d]-1;8008+ if (dn->digits>1 && *up<powers[d-1]) {8009+ #if DECTRACE || DECVERB8010+ printf("Leading 0 in number.\n");8011+ decNumberShow(dn);8012+ #endif8013+ return 1;}8014+ }8015+ if (*up>maxuint) {8016+ #if DECTRACE || DECVERB8017+ printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",8018+ (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);8019+ #endif8020+ return 1;}8021+ d-=DECDPUN;8022+ }8023+8024+ // check the exponent. Note that input operands can have exponents8025+ // which are out of the set->emin/set->emax and set->digits range8026+ // (just as they can have more digits than set->digits).8027+ ae=dn->exponent+dn->digits-1; // adjusted exponent8028+ emax=DECNUMMAXE;8029+ emin=DECNUMMINE;8030+ digits=DECNUMMAXP;8031+ if (ae<emin-(digits-1)) {8032+ #if DECTRACE || DECVERB8033+ printf("Adjusted exponent underflow [%ld].\n", (LI)ae);8034+ decNumberShow(dn);8035+ #endif8036+ return 1;}8037+ if (ae>+emax) {8038+ #if DECTRACE || DECVERB8039+ printf("Adjusted exponent overflow [%ld].\n", (LI)ae);8040+ decNumberShow(dn);8041+ #endif8042+ return 1;}8043+8044+ return 0; // it's OK8045+ } // decCheckNumber8046+8047+/* ------------------------------------------------------------------ */8048+/* decCheckInexact -- check a normal finite inexact result has digits */8049+/* dn is the number to check */8050+/* set is the context (for status and precision) */8051+/* sets Invalid operation, etc., if some digits are missing */8052+/* [this check is not made for DECSUBSET compilation or when */8053+/* subnormal is not set] */8054+/* ------------------------------------------------------------------ */8055+static void decCheckInexact(const decNumber *dn, decContext *set) {8056+ #if !DECSUBSET && DECEXTFLAG8057+ if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact8058+ && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {8059+ #if DECTRACE || DECVERB8060+ printf("Insufficient digits [%ld] on normal Inexact result.\n",8061+ (LI)dn->digits);8062+ decNumberShow(dn);8063+ #endif8064+ decContextSetStatus(set, DEC_Invalid_operation);8065+ }8066+ #else8067+ // next is a noop for quiet compiler8068+ if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;8069+ #endif8070+ return;8071+ } // decCheckInexact8072+#endif8073+8074+#if DECALLOC8075+#undef malloc8076+#undef free8077+/* ------------------------------------------------------------------ */8078+/* decMalloc -- accountable allocation routine */8079+/* n is the number of bytes to allocate */8080+/* */8081+/* Semantics is the same as the stdlib malloc routine, but bytes */8082+/* allocated are accounted for globally, and corruption fences are */8083+/* added before and after the 'actual' storage. */8084+/* ------------------------------------------------------------------ */8085+/* This routine allocates storage with an extra twelve bytes; 8 are */8086+/* at the start and hold: */8087+/* 0-3 the original length requested */8088+/* 4-7 buffer corruption detection fence (DECFENCE, x4) */8089+/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */8090+/* ------------------------------------------------------------------ */8091+static void *decMalloc(size_t n) {8092+ uInt size=n+12; // true size8093+ void *alloc; // -> allocated storage8094+ uByte *b, *b0; // work8095+ uInt uiwork; // for macros8096+8097+ alloc=malloc(size); // -> allocated storage8098+ if (alloc==NULL) return NULL; // out of strorage8099+ b0=(uByte *)alloc; // as bytes8100+ decAllocBytes+=n; // account for storage8101+ UBFROMUI(alloc, n); // save n8102+ // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);8103+ for (b=b0+4; b<b0+8; b++) *b=DECFENCE;8104+ for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;8105+ return b0+8; // -> play area8106+ } // decMalloc8107+8108+/* ------------------------------------------------------------------ */8109+/* decFree -- accountable free routine */8110+/* alloc is the storage to free */8111+/* */8112+/* Semantics is the same as the stdlib malloc routine, except that */8113+/* the global storage accounting is updated and the fences are */8114+/* checked to ensure that no routine has written 'out of bounds'. */8115+/* ------------------------------------------------------------------ */8116+/* This routine first checks that the fences have not been corrupted. */8117+/* It then frees the storage using the 'truw' storage address (that */8118+/* is, offset by 8). */8119+/* ------------------------------------------------------------------ */8120+static void decFree(void *alloc) {8121+ uInt n; // original length8122+ uByte *b, *b0; // work8123+ uInt uiwork; // for macros8124+8125+ if (alloc==NULL) return; // allowed; it's a nop8126+ b0=(uByte *)alloc; // as bytes8127+ b0-=8; // -> true start of storage8128+ n=UBTOUI(b0); // lift length8129+ for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)8130+ printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,8131+ b-b0-8, (LI)b0);8132+ for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)8133+ printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,8134+ b-b0-8, (LI)b0, (LI)n);8135+ free(b0); // drop the storage8136+ decAllocBytes-=n; // account for storage8137+ // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);8138+ } // decFree8139+#define malloc(a) decMalloc(a)8140+#define free(a) decFree(a)8141+#endifadded:src/decNumber/decNumber.h+182 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number arithmetic module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECNUMBER)21+ #define DECNUMBER22+ #define DECNAME "decNumber" /* Short name */23+ #define DECFULLNAME "Decimal Number Module" /* Verbose name */24+ #define DECAUTHOR "Mike Cowlishaw" /* Who to blame */25+26+ #if !defined(DECCONTEXT)27+ #include "decContext.h"28+ #endif29+30+ /* Bit settings for decNumber.bits */31+ #define DECNEG 0x80 /* Sign; 1=negative, 0=positive or zero */32+ #define DECINF 0x40 /* 1=Infinity */33+ #define DECNAN 0x20 /* 1=NaN */34+ #define DECSNAN 0x10 /* 1=sNaN */35+ /* The remaining bits are reserved; they must be 0 */36+ #define DECSPECIAL (DECINF|DECNAN|DECSNAN) /* any special value */37+38+ /* Define the decNumber data structure. The size and shape of the */39+ /* units array in the structure is determined by the following */40+ /* constant. This must not be changed without recompiling the */41+ /* decNumber library modules. */42+43+ #define DECDPUN 3 /* DECimal Digits Per UNit [must be >0 */44+ /* and <10; 3 or powers of 2 are best]. */45+46+ /* DECNUMDIGITS is the default number of digits that can be held in */47+ /* the structure. If undefined, 1 is assumed and it is assumed */48+ /* that the structure will be immediately followed by extra space, */49+ /* as required. DECNUMDIGITS is always >0. */50+ #if !defined(DECNUMDIGITS)51+ #define DECNUMDIGITS 152+ #endif53+54+ /* The size (integer data type) of each unit is determined by the */55+ /* number of digits it will hold. */56+ #if DECDPUN<=257+ #define decNumberUnit uint8_t58+ #elif DECDPUN<=459+ #define decNumberUnit uint16_t60+ #else61+ #define decNumberUnit uint32_t62+ #endif63+ /* The number of units needed is ceil(DECNUMDIGITS/DECDPUN) */64+ #define DECNUMUNITS ((DECNUMDIGITS+DECDPUN-1)/DECDPUN)65+66+ /* The data structure... */67+ typedef struct {68+ int32_t digits; /* Count of digits in the coefficient; >0 */69+ int32_t exponent; /* Unadjusted exponent, unbiased, in */70+ /* range: -1999999997 through 999999999 */71+ uint8_t bits; /* Indicator bits (see above) */72+ /* Coefficient, from least significant unit */73+ decNumberUnit lsu[DECNUMUNITS];74+ } decNumber;75+76+ /* Notes: */77+ /* 1. If digits is > DECDPUN then there will one or more */78+ /* decNumberUnits immediately following the first element of lsu.*/79+ /* These contain the remaining (more significant) digits of the */80+ /* number, and may be in the lsu array, or may be guaranteed by */81+ /* some other mechanism (such as being contained in another */82+ /* structure, or being overlaid on dynamically allocated */83+ /* storage). */84+ /* */85+ /* Each integer of the coefficient (except potentially the last) */86+ /* contains DECDPUN digits (e.g., a value in the range 0 through */87+ /* 99999999 if DECDPUN is 8, or 0 through 999 if DECDPUN is 3). */88+ /* */89+ /* 2. A decNumber converted to a string may need up to digits+14 */90+ /* characters. The worst cases (non-exponential and exponential */91+ /* formats) are -0.00000{9...}# and -9.{9...}E+999999999# */92+ /* (where # is '\0') */93+94+95+ /* ---------------------------------------------------------------- */96+ /* decNumber public functions and macros */97+ /* ---------------------------------------------------------------- */98+ /* Conversions */99+ decNumber * decNumberFromInt32(decNumber *, int32_t);100+ decNumber * decNumberFromUInt32(decNumber *, uint32_t);101+ decNumber * decNumberFromString(decNumber *, const char *, decContext *);102+ char * decNumberToString(const decNumber *, char *);103+ char * decNumberToEngString(const decNumber *, char *);104+ uint32_t decNumberToUInt32(const decNumber *, decContext *);105+ int32_t decNumberToInt32(const decNumber *, decContext *);106+ uint8_t * decNumberGetBCD(const decNumber *, uint8_t *);107+ decNumber * decNumberSetBCD(decNumber *, const uint8_t *, uint32_t);108+109+ /* Operators and elementary functions */110+ decNumber * decNumberAbs(decNumber *, const decNumber *, decContext *);111+ decNumber * decNumberAdd(decNumber *, const decNumber *, const decNumber *, decContext *);112+ decNumber * decNumberAnd(decNumber *, const decNumber *, const decNumber *, decContext *);113+ decNumber * decNumberCompare(decNumber *, const decNumber *, const decNumber *, decContext *);114+ decNumber * decNumberCompareSignal(decNumber *, const decNumber *, const decNumber *, decContext *);115+ decNumber * decNumberCompareTotal(decNumber *, const decNumber *, const decNumber *, decContext *);116+ decNumber * decNumberCompareTotalMag(decNumber *, const decNumber *, const decNumber *, decContext *);117+ decNumber * decNumberDivide(decNumber *, const decNumber *, const decNumber *, decContext *);118+ decNumber * decNumberDivideInteger(decNumber *, const decNumber *, const decNumber *, decContext *);119+ decNumber * decNumberExp(decNumber *, const decNumber *, decContext *);120+ decNumber * decNumberFMA(decNumber *, const decNumber *, const decNumber *, const decNumber *, decContext *);121+ decNumber * decNumberInvert(decNumber *, const decNumber *, decContext *);122+ decNumber * decNumberLn(decNumber *, const decNumber *, decContext *);123+ decNumber * decNumberLogB(decNumber *, const decNumber *, decContext *);124+ decNumber * decNumberLog10(decNumber *, const decNumber *, decContext *);125+ decNumber * decNumberMax(decNumber *, const decNumber *, const decNumber *, decContext *);126+ decNumber * decNumberMaxMag(decNumber *, const decNumber *, const decNumber *, decContext *);127+ decNumber * decNumberMin(decNumber *, const decNumber *, const decNumber *, decContext *);128+ decNumber * decNumberMinMag(decNumber *, const decNumber *, const decNumber *, decContext *);129+ decNumber * decNumberMinus(decNumber *, const decNumber *, decContext *);130+ decNumber * decNumberMultiply(decNumber *, const decNumber *, const decNumber *, decContext *);131+ decNumber * decNumberNormalize(decNumber *, const decNumber *, decContext *);132+ decNumber * decNumberOr(decNumber *, const decNumber *, const decNumber *, decContext *);133+ decNumber * decNumberPlus(decNumber *, const decNumber *, decContext *);134+ decNumber * decNumberPower(decNumber *, const decNumber *, const decNumber *, decContext *);135+ decNumber * decNumberQuantize(decNumber *, const decNumber *, const decNumber *, decContext *);136+ decNumber * decNumberReduce(decNumber *, const decNumber *, decContext *);137+ decNumber * decNumberRemainder(decNumber *, const decNumber *, const decNumber *, decContext *);138+ decNumber * decNumberRemainderNear(decNumber *, const decNumber *, const decNumber *, decContext *);139+ decNumber * decNumberRescale(decNumber *, const decNumber *, const decNumber *, decContext *);140+ decNumber * decNumberRotate(decNumber *, const decNumber *, const decNumber *, decContext *);141+ decNumber * decNumberSameQuantum(decNumber *, const decNumber *, const decNumber *);142+ decNumber * decNumberScaleB(decNumber *, const decNumber *, const decNumber *, decContext *);143+ decNumber * decNumberShift(decNumber *, const decNumber *, const decNumber *, decContext *);144+ decNumber * decNumberSquareRoot(decNumber *, const decNumber *, decContext *);145+ decNumber * decNumberSubtract(decNumber *, const decNumber *, const decNumber *, decContext *);146+ decNumber * decNumberToIntegralExact(decNumber *, const decNumber *, decContext *);147+ decNumber * decNumberToIntegralValue(decNumber *, const decNumber *, decContext *);148+ decNumber * decNumberXor(decNumber *, const decNumber *, const decNumber *, decContext *);149+150+ /* Utilities */151+ enum decClass decNumberClass(const decNumber *, decContext *);152+ const char * decNumberClassToString(enum decClass);153+ decNumber * decNumberCopy(decNumber *, const decNumber *);154+ decNumber * decNumberCopyAbs(decNumber *, const decNumber *);155+ decNumber * decNumberCopyNegate(decNumber *, const decNumber *);156+ decNumber * decNumberCopySign(decNumber *, const decNumber *, const decNumber *);157+ decNumber * decNumberNextMinus(decNumber *, const decNumber *, decContext *);158+ decNumber * decNumberNextPlus(decNumber *, const decNumber *, decContext *);159+ decNumber * decNumberNextToward(decNumber *, const decNumber *, const decNumber *, decContext *);160+ decNumber * decNumberTrim(decNumber *);161+ const char * decNumberVersion(void);162+ decNumber * decNumberZero(decNumber *);163+164+ /* Functions for testing decNumbers (normality depends on context) */165+ int32_t decNumberIsNormal(const decNumber *, decContext *);166+ int32_t decNumberIsSubnormal(const decNumber *, decContext *);167+168+ /* Macros for testing decNumber *dn */169+ #define decNumberIsCanonical(dn) (1) /* All decNumbers are saintly */170+ #define decNumberIsFinite(dn) (((dn)->bits&DECSPECIAL)==0)171+ #define decNumberIsInfinite(dn) (((dn)->bits&DECINF)!=0)172+ #define decNumberIsNaN(dn) (((dn)->bits&(DECNAN|DECSNAN))!=0)173+ #define decNumberIsNegative(dn) (((dn)->bits&DECNEG)!=0)174+ #define decNumberIsQNaN(dn) (((dn)->bits&(DECNAN))!=0)175+ #define decNumberIsSNaN(dn) (((dn)->bits&(DECSNAN))!=0)176+ #define decNumberIsSpecial(dn) (((dn)->bits&DECSPECIAL)!=0)177+ #define decNumberIsZero(dn) (*(dn)->lsu==0 \178+ && (dn)->digits==1 \179+ && (((dn)->bits&DECSPECIAL)==0))180+ #define decNumberRadix(dn) (10)181+182+#endifadded:src/decNumber/decnumber.pdfbinary
A binary file, added.
added:src/decNumber/decNumberLocal.h+757 added
1+/* ------------------------------------------------------------------ */2+/* decNumber package local type, tuning, and macro definitions */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This header file is included by all modules in the decNumber */20+/* library, and contains local type definitions, tuning parameters, */21+/* etc. It should not need to be used by application programs. */22+/* decNumber.h or one of decDouble (etc.) must be included first. */23+/* ------------------------------------------------------------------ */24+25+#if !defined(DECNUMBERLOC)26+ #define DECNUMBERLOC27+ #define DECVERSION "decNumber 3.68" /* Package Version [16 max.] */28+ #define DECNLAUTHOR "Mike Cowlishaw" /* Who to blame */29+30+ #include <stdlib.h> /* for abs */31+ #include <string.h> /* for memset, strcpy */32+33+ /* Conditional code flag -- set this to match hardware platform */34+ #if !defined(DECLITEND)35+ #define DECLITEND 1 /* 1=little-endian, 0=big-endian */36+ #endif37+38+ /* Conditional code flag -- set this to 1 for best performance */39+ #if !defined(DECUSE64)40+ #define DECUSE64 1 /* 1=use int64s, 0=int32 & smaller only */41+ #endif42+43+ /* Conditional code flag -- set this to 0 to exclude printf calls */44+ #if !defined(DECPRINT)45+ #define DECPRINT 1 /* 1=allow printf calls; 0=no printf */46+ #endif47+48+ /* Conditional check flags -- set these to 0 for best performance */49+ #if !defined(DECCHECK)50+ #define DECCHECK 0 /* 1 to enable robust checking */51+ #endif52+ #if !defined(DECALLOC)53+ #define DECALLOC 0 /* 1 to enable memory accounting */54+ #endif55+ #if !defined(DECTRACE)56+ #define DECTRACE 0 /* 1 to trace certain internals, etc. */57+ #endif58+59+ /* Tuning parameter for decNumber (arbitrary precision) module */60+ #if !defined(DECBUFFER)61+ #define DECBUFFER 36 /* Size basis for local buffers. This */62+ /* should be a common maximum precision */63+ /* rounded up to a multiple of 4; must */64+ /* be zero or positive. */65+ #endif66+67+68+ /* ---------------------------------------------------------------- */69+ /* Check parameter dependencies */70+ /* ---------------------------------------------------------------- */71+ #if DECCHECK & !DECPRINT72+ #error DECCHECK needs DECPRINT to be useful73+ #endif74+ #if DECALLOC & !DECPRINT75+ #error DECALLOC needs DECPRINT to be useful76+ #endif77+ #if DECTRACE & !DECPRINT78+ #error DECTRACE needs DECPRINT to be useful79+ #endif80+81+ /* ---------------------------------------------------------------- */82+ /* Definitions for all modules (general-purpose) */83+ /* ---------------------------------------------------------------- */84+85+ /* Local names for common types -- for safety, decNumber modules do */86+ /* not use int or long directly. */87+ #define Flag uint8_t88+ #define Byte int8_t89+ #define uByte uint8_t90+ #define Short int16_t91+ #define uShort uint16_t92+ #define Int int32_t93+ #define uInt uint32_t94+ #define Unit decNumberUnit95+ #if DECUSE6496+ #define Long int64_t97+ #define uLong uint64_t98+ #endif99+100+ /* Development-use definitions */101+ typedef long int LI; /* for printf arguments only */102+ #define DECNOINT 0 /* 1 to check no internal use of 'int' */103+ /* or stdint types */104+ #if DECNOINT105+ /* if these interfere with your C includes, do not set DECNOINT */106+ #define int ? /* enable to ensure that plain C 'int' */107+ #define long ?? /* .. or 'long' types are not used */108+ #endif109+110+ /* Shared lookup tables */111+ extern const uByte DECSTICKYTAB[10]; /* re-round digits if sticky */112+ extern const uInt DECPOWERS[10]; /* powers of ten table */113+ /* The following are included from decDPD.h */114+ extern const uShort DPD2BIN[1024]; /* DPD -> 0-999 */115+ extern const uShort BIN2DPD[1000]; /* 0-999 -> DPD */116+ extern const uInt DPD2BINK[1024]; /* DPD -> 0-999000 */117+ extern const uInt DPD2BINM[1024]; /* DPD -> 0-999000000 */118+ extern const uByte DPD2BCD8[4096]; /* DPD -> ddd + len */119+ extern const uByte BIN2BCD8[4000]; /* 0-999 -> ddd + len */120+ extern const uShort BCD2DPD[2458]; /* 0-0x999 -> DPD (0x999=2457)*/121+122+ /* LONGMUL32HI -- set w=(u*v)>>32, where w, u, and v are uInts */123+ /* (that is, sets w to be the high-order word of the 64-bit result; */124+ /* the low-order word is simply u*v.) */125+ /* This version is derived from Knuth via Hacker's Delight; */126+ /* it seems to optimize better than some others tried */127+ #define LONGMUL32HI(w, u, v) { \128+ uInt u0, u1, v0, v1, w0, w1, w2, t; \129+ u0=u & 0xffff; u1=u>>16; \130+ v0=v & 0xffff; v1=v>>16; \131+ w0=u0*v0; \132+ t=u1*v0 + (w0>>16); \133+ w1=t & 0xffff; w2=t>>16; \134+ w1=u0*v1 + w1; \135+ (w)=u1*v1 + w2 + (w1>>16);}136+137+ /* ROUNDUP -- round an integer up to a multiple of n */138+ #define ROUNDUP(i, n) ((((i)+(n)-1)/n)*n)139+ #define ROUNDUP4(i) (((i)+3)&~3) /* special for n=4 */140+141+ /* ROUNDDOWN -- round an integer down to a multiple of n */142+ #define ROUNDDOWN(i, n) (((i)/n)*n)143+ #define ROUNDDOWN4(i) ((i)&~3) /* special for n=4 */144+145+ /* References to multi-byte sequences under different sizes; these */146+ /* require locally declared variables, but do not violate strict */147+ /* aliasing or alignment (as did the UINTAT simple cast to uInt). */148+ /* Variables needed are uswork, uiwork, etc. [so do not use at same */149+ /* level in an expression, e.g., UBTOUI(x)==UBTOUI(y) may fail]. */150+151+ /* Return a uInt, etc., from bytes starting at a char* or uByte* */152+ #define UBTOUS(b) (memcpy((void *)&uswork, b, 2), uswork)153+ #define UBTOUI(b) (memcpy((void *)&uiwork, b, 4), uiwork)154+155+ /* Store a uInt, etc., into bytes starting at a char* or uByte*. */156+ /* Returns i, evaluated, for convenience; has to use uiwork because */157+ /* i may be an expression. */158+ #define UBFROMUS(b, i) (uswork=(i), memcpy(b, (void *)&uswork, 2), uswork)159+ #define UBFROMUI(b, i) (uiwork=(i), memcpy(b, (void *)&uiwork, 4), uiwork)160+161+ /* X10 and X100 -- multiply integer i by 10 or 100 */162+ /* [shifts are usually faster than multiply; could be conditional] */163+ #define X10(i) (((i)<<1)+((i)<<3))164+ #define X100(i) (((i)<<2)+((i)<<5)+((i)<<6))165+166+ /* MAXI and MINI -- general max & min (not in ANSI) for integers */167+ #define MAXI(x,y) ((x)<(y)?(y):(x))168+ #define MINI(x,y) ((x)>(y)?(y):(x))169+170+ /* Useful constants */171+ #define BILLION 1000000000 /* 10**9 */172+ /* CHARMASK: 0x30303030 for ASCII/UTF8; 0xF0F0F0F0 for EBCDIC */173+ #define CHARMASK ((((((((uInt)'0')<<8)+'0')<<8)+'0')<<8)+'0')174+175+176+ /* ---------------------------------------------------------------- */177+ /* Definitions for arbitary-precision modules (only valid after */178+ /* decNumber.h has been included) */179+ /* ---------------------------------------------------------------- */180+181+ /* Limits and constants */182+ #define DECNUMMAXP 999999999 /* maximum precision code can handle */183+ #define DECNUMMAXE 999999999 /* maximum adjusted exponent ditto */184+ #define DECNUMMINE -999999999 /* minimum adjusted exponent ditto */185+ #if (DECNUMMAXP != DEC_MAX_DIGITS)186+ #error Maximum digits mismatch187+ #endif188+ #if (DECNUMMAXE != DEC_MAX_EMAX)189+ #error Maximum exponent mismatch190+ #endif191+ #if (DECNUMMINE != DEC_MIN_EMIN)192+ #error Minimum exponent mismatch193+ #endif194+195+ /* Set DECDPUNMAX -- the maximum integer that fits in DECDPUN */196+ /* digits, and D2UTABLE -- the initializer for the D2U table */197+ #if DECDPUN==1198+ #define DECDPUNMAX 9199+ #define D2UTABLE {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, \200+ 18,19,20,21,22,23,24,25,26,27,28,29,30,31,32, \201+ 33,34,35,36,37,38,39,40,41,42,43,44,45,46,47, \202+ 48,49}203+ #elif DECDPUN==2204+ #define DECDPUNMAX 99205+ #define D2UTABLE {0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10, \206+ 11,11,12,12,13,13,14,14,15,15,16,16,17,17,18, \207+ 18,19,19,20,20,21,21,22,22,23,23,24,24,25}208+ #elif DECDPUN==3209+ #define DECDPUNMAX 999210+ #define D2UTABLE {0,1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7, \211+ 8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13,13, \212+ 13,14,14,14,15,15,15,16,16,16,17}213+ #elif DECDPUN==4214+ #define DECDPUNMAX 9999215+ #define D2UTABLE {0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6, \216+ 6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11, \217+ 11,11,11,12,12,12,12,13}218+ #elif DECDPUN==5219+ #define DECDPUNMAX 99999220+ #define D2UTABLE {0,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5, \221+ 5,5,5,5,6,6,6,6,6,7,7,7,7,7,8,8,8,8,8,9,9,9, \222+ 9,9,10,10,10,10}223+ #elif DECDPUN==6224+ #define DECDPUNMAX 999999225+ #define D2UTABLE {0,1,1,1,1,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4,4,4, \226+ 4,4,4,5,5,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,8, \227+ 8,8,8,8,8,9}228+ #elif DECDPUN==7229+ #define DECDPUNMAX 9999999230+ #define D2UTABLE {0,1,1,1,1,1,1,1,2,2,2,2,2,2,2,3,3,3,3,3,3,3, \231+ 4,4,4,4,4,4,4,5,5,5,5,5,5,5,6,6,6,6,6,6,6,7, \232+ 7,7,7,7,7,7}233+ #elif DECDPUN==8234+ #define DECDPUNMAX 99999999235+ #define D2UTABLE {0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3, \236+ 3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6, \237+ 6,6,6,6,6,7}238+ #elif DECDPUN==9239+ #define DECDPUNMAX 999999999240+ #define D2UTABLE {0,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3, \241+ 3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5, \242+ 5,5,6,6,6,6}243+ #elif defined(DECDPUN)244+ #error DECDPUN must be in the range 1-9245+ #endif246+247+ /* ----- Shared data (in decNumber.c) ----- */248+ /* Public lookup table used by the D2U macro (see below) */249+ #define DECMAXD2U 49250+ extern const uByte d2utable[DECMAXD2U+1];251+252+ /* ----- Macros ----- */253+ /* ISZERO -- return true if decNumber dn is a zero */254+ /* [performance-critical in some situations] */255+ #define ISZERO(dn) decNumberIsZero(dn) /* now just a local name */256+257+ /* D2U -- return the number of Units needed to hold d digits */258+ /* (runtime version, with table lookaside for small d) */259+ #if DECDPUN==8260+ #define D2U(d) ((unsigned)((d)<=DECMAXD2U?d2utable[d]:((d)+7)>>3))261+ #elif DECDPUN==4262+ #define D2U(d) ((unsigned)((d)<=DECMAXD2U?d2utable[d]:((d)+3)>>2))263+ #else264+ #define D2U(d) ((d)<=DECMAXD2U?d2utable[d]:((d)+DECDPUN-1)/DECDPUN)265+ #endif266+ /* SD2U -- static D2U macro (for compile-time calculation) */267+ #define SD2U(d) (((d)+DECDPUN-1)/DECDPUN)268+269+ /* MSUDIGITS -- returns digits in msu, from digits, calculated */270+ /* using D2U */271+ #define MSUDIGITS(d) ((d)-(D2U(d)-1)*DECDPUN)272+273+ /* D2N -- return the number of decNumber structs that would be */274+ /* needed to contain that number of digits (and the initial */275+ /* decNumber struct) safely. Note that one Unit is included in the */276+ /* initial structure. Used for allocating space that is aligned on */277+ /* a decNumber struct boundary. */278+ #define D2N(d) \279+ ((((SD2U(d)-1)*sizeof(Unit))+sizeof(decNumber)*2-1)/sizeof(decNumber))280+281+ /* TODIGIT -- macro to remove the leading digit from the unsigned */282+ /* integer u at column cut (counting from the right, LSD=0) and */283+ /* place it as an ASCII character into the character pointed to by */284+ /* c. Note that cut must be <= 9, and the maximum value for u is */285+ /* 2,000,000,000 (as is needed for negative exponents of */286+ /* subnormals). The unsigned integer pow is used as a temporary */287+ /* variable. */288+ #define TODIGIT(u, cut, c, pow) { \289+ *(c)='0'; \290+ pow=DECPOWERS[cut]*2; \291+ if ((u)>pow) { \292+ pow*=4; \293+ if ((u)>=pow) {(u)-=pow; *(c)+=8;} \294+ pow/=2; \295+ if ((u)>=pow) {(u)-=pow; *(c)+=4;} \296+ pow/=2; \297+ } \298+ if ((u)>=pow) {(u)-=pow; *(c)+=2;} \299+ pow/=2; \300+ if ((u)>=pow) {(u)-=pow; *(c)+=1;} \301+ }302+303+ /* ---------------------------------------------------------------- */304+ /* Definitions for fixed-precision modules (only valid after */305+ /* decSingle.h, decDouble.h, or decQuad.h has been included) */306+ /* ---------------------------------------------------------------- */307+308+ /* bcdnum -- a structure describing a format-independent finite */309+ /* number, whose coefficient is a string of bcd8 uBytes */310+ typedef struct {311+ uByte *msd; /* -> most significant digit */312+ uByte *lsd; /* -> least ditto */313+ uInt sign; /* 0=positive, DECFLOAT_Sign=negative */314+ Int exponent; /* Unadjusted signed exponent (q), or */315+ /* DECFLOAT_NaN etc. for a special */316+ } bcdnum;317+318+ /* Test if exponent or bcdnum exponent must be a special, etc. */319+ #define EXPISSPECIAL(exp) ((exp)>=DECFLOAT_MinSp)320+ #define EXPISINF(exp) (exp==DECFLOAT_Inf)321+ #define EXPISNAN(exp) (exp==DECFLOAT_qNaN || exp==DECFLOAT_sNaN)322+ #define NUMISSPECIAL(num) (EXPISSPECIAL((num)->exponent))323+324+ /* Refer to a 32-bit word or byte in a decFloat (df) by big-endian */325+ /* (array) notation (the 0 word or byte contains the sign bit), */326+ /* automatically adjusting for endianness; similarly address a word */327+ /* in the next-wider format (decFloatWider, or dfw) */328+ #define DECWORDS (DECBYTES/4)329+ #define DECWWORDS (DECWBYTES/4)330+ #if DECLITEND331+ #define DFBYTE(df, off) ((df)->bytes[DECBYTES-1-(off)])332+ #define DFWORD(df, off) ((df)->words[DECWORDS-1-(off)])333+ #define DFWWORD(dfw, off) ((dfw)->words[DECWWORDS-1-(off)])334+ #else335+ #define DFBYTE(df, off) ((df)->bytes[off])336+ #define DFWORD(df, off) ((df)->words[off])337+ #define DFWWORD(dfw, off) ((dfw)->words[off])338+ #endif339+340+ /* Tests for sign or specials, directly on DECFLOATs */341+ #define DFISSIGNED(df) ((DFWORD(df, 0)&0x80000000)!=0)342+ #define DFISSPECIAL(df) ((DFWORD(df, 0)&0x78000000)==0x78000000)343+ #define DFISINF(df) ((DFWORD(df, 0)&0x7c000000)==0x78000000)344+ #define DFISNAN(df) ((DFWORD(df, 0)&0x7c000000)==0x7c000000)345+ #define DFISQNAN(df) ((DFWORD(df, 0)&0x7e000000)==0x7c000000)346+ #define DFISSNAN(df) ((DFWORD(df, 0)&0x7e000000)==0x7e000000)347+348+ /* Shared lookup tables */349+ extern const uInt DECCOMBMSD[64]; /* Combination field -> MSD */350+ extern const uInt DECCOMBFROM[48]; /* exp+msd -> Combination */351+352+ /* Private generic (utility) routine */353+ #if DECCHECK || DECTRACE354+ extern void decShowNum(const bcdnum *, const char *);355+ #endif356+357+ /* Format-dependent macros and constants */358+ #if defined(DECPMAX)359+360+ /* Useful constants */361+ #define DECPMAX9 (ROUNDUP(DECPMAX, 9)/9) /* 'Pmax' in 10**9s */362+ /* Top words for a zero */363+ #define SINGLEZERO 0x22500000364+ #define DOUBLEZERO 0x22380000365+ #define QUADZERO 0x22080000366+ /* [ZEROWORD is defined to be one of these in the DFISZERO macro] */367+368+ /* Format-dependent common tests: */369+ /* DFISZERO -- test for (any) zero */370+ /* DFISCCZERO -- test for coefficient continuation being zero */371+ /* DFISCC01 -- test for coefficient contains only 0s and 1s */372+ /* DFISINT -- test for finite and exponent q=0 */373+ /* DFISUINT01 -- test for sign=0, finite, exponent q=0, and */374+ /* MSD=0 or 1 */375+ /* ZEROWORD is also defined here. */376+ /* */377+ /* In DFISZERO the first test checks the least-significant word */378+ /* (most likely to be non-zero); the penultimate tests MSD and */379+ /* DPDs in the signword, and the final test excludes specials and */380+ /* MSD>7. DFISINT similarly has to allow for the two forms of */381+ /* MSD codes. DFISUINT01 only has to allow for one form of MSD */382+ /* code. */383+ #if DECPMAX==7384+ #define ZEROWORD SINGLEZERO385+ /* [test macros not needed except for Zero] */386+ #define DFISZERO(df) ((DFWORD(df, 0)&0x1c0fffff)==0 \387+ && (DFWORD(df, 0)&0x60000000)!=0x60000000)388+ #elif DECPMAX==16389+ #define ZEROWORD DOUBLEZERO390+ #define DFISZERO(df) ((DFWORD(df, 1)==0 \391+ && (DFWORD(df, 0)&0x1c03ffff)==0 \392+ && (DFWORD(df, 0)&0x60000000)!=0x60000000))393+ #define DFISINT(df) ((DFWORD(df, 0)&0x63fc0000)==0x22380000 \394+ ||(DFWORD(df, 0)&0x7bfc0000)==0x6a380000)395+ #define DFISUINT01(df) ((DFWORD(df, 0)&0xfbfc0000)==0x22380000)396+ #define DFISCCZERO(df) (DFWORD(df, 1)==0 \397+ && (DFWORD(df, 0)&0x0003ffff)==0)398+ #define DFISCC01(df) ((DFWORD(df, 0)&~0xfffc9124)==0 \399+ && (DFWORD(df, 1)&~0x49124491)==0)400+ #elif DECPMAX==34401+ #define ZEROWORD QUADZERO402+ #define DFISZERO(df) ((DFWORD(df, 3)==0 \403+ && DFWORD(df, 2)==0 \404+ && DFWORD(df, 1)==0 \405+ && (DFWORD(df, 0)&0x1c003fff)==0 \406+ && (DFWORD(df, 0)&0x60000000)!=0x60000000))407+ #define DFISINT(df) ((DFWORD(df, 0)&0x63ffc000)==0x22080000 \408+ ||(DFWORD(df, 0)&0x7bffc000)==0x6a080000)409+ #define DFISUINT01(df) ((DFWORD(df, 0)&0xfbffc000)==0x22080000)410+ #define DFISCCZERO(df) (DFWORD(df, 3)==0 \411+ && DFWORD(df, 2)==0 \412+ && DFWORD(df, 1)==0 \413+ && (DFWORD(df, 0)&0x00003fff)==0)414+415+ #define DFISCC01(df) ((DFWORD(df, 0)&~0xffffc912)==0 \416+ && (DFWORD(df, 1)&~0x44912449)==0 \417+ && (DFWORD(df, 2)&~0x12449124)==0 \418+ && (DFWORD(df, 3)&~0x49124491)==0)419+ #endif420+421+ /* Macros to test if a certain 10 bits of a uInt or pair of uInts */422+ /* are a canonical declet [higher or lower bits are ignored]. */423+ /* declet is at offset 0 (from the right) in a uInt: */424+ #define CANONDPD(dpd) (((dpd)&0x300)==0 || ((dpd)&0x6e)!=0x6e)425+ /* declet is at offset k (a multiple of 2) in a uInt: */426+ #define CANONDPDOFF(dpd, k) (((dpd)&(0x300<<(k)))==0 \427+ || ((dpd)&(((uInt)0x6e)<<(k)))!=(((uInt)0x6e)<<(k)))428+ /* declet is at offset k (a multiple of 2) in a pair of uInts: */429+ /* [the top 2 bits will always be in the more-significant uInt] */430+ #define CANONDPDTWO(hi, lo, k) (((hi)&(0x300>>(32-(k))))==0 \431+ || ((hi)&(0x6e>>(32-(k))))!=(0x6e>>(32-(k))) \432+ || ((lo)&(((uInt)0x6e)<<(k)))!=(((uInt)0x6e)<<(k)))433+434+ /* Macro to test whether a full-length (length DECPMAX) BCD8 */435+ /* coefficient, starting at uByte u, is all zeros */436+ /* Test just the LSWord first, then the remainder as a sequence */437+ /* of tests in order to avoid same-level use of UBTOUI */438+ #if DECPMAX==7439+ #define ISCOEFFZERO(u) ( \440+ UBTOUI((u)+DECPMAX-4)==0 \441+ && UBTOUS((u)+DECPMAX-6)==0 \442+ && *(u)==0)443+ #elif DECPMAX==16444+ #define ISCOEFFZERO(u) ( \445+ UBTOUI((u)+DECPMAX-4)==0 \446+ && UBTOUI((u)+DECPMAX-8)==0 \447+ && UBTOUI((u)+DECPMAX-12)==0 \448+ && UBTOUI(u)==0)449+ #elif DECPMAX==34450+ #define ISCOEFFZERO(u) ( \451+ UBTOUI((u)+DECPMAX-4)==0 \452+ && UBTOUI((u)+DECPMAX-8)==0 \453+ && UBTOUI((u)+DECPMAX-12)==0 \454+ && UBTOUI((u)+DECPMAX-16)==0 \455+ && UBTOUI((u)+DECPMAX-20)==0 \456+ && UBTOUI((u)+DECPMAX-24)==0 \457+ && UBTOUI((u)+DECPMAX-28)==0 \458+ && UBTOUI((u)+DECPMAX-32)==0 \459+ && UBTOUS(u)==0)460+ #endif461+462+ /* Macros and masks for the sign, exponent continuation, and MSD */463+ /* Get the sign as DECFLOAT_Sign or 0 */464+ #define GETSIGN(df) (DFWORD(df, 0)&0x80000000)465+ /* Get the exponent continuation from a decFloat *df as an Int */466+ #define GETECON(df) ((Int)((DFWORD((df), 0)&0x03ffffff)>>(32-6-DECECONL)))467+ /* Ditto, from the next-wider format */468+ #define GETWECON(df) ((Int)((DFWWORD((df), 0)&0x03ffffff)>>(32-6-DECWECONL)))469+ /* Get the biased exponent similarly */470+ #define GETEXP(df) ((Int)(DECCOMBEXP[DFWORD((df), 0)>>26]+GETECON(df)))471+ /* Get the unbiased exponent similarly */472+ #define GETEXPUN(df) ((Int)GETEXP(df)-DECBIAS)473+ /* Get the MSD similarly (as uInt) */474+ #define GETMSD(df) (DECCOMBMSD[DFWORD((df), 0)>>26])475+476+ /* Compile-time computes of the exponent continuation field masks */477+ /* full exponent continuation field: */478+ #define ECONMASK ((0x03ffffff>>(32-6-DECECONL))<<(32-6-DECECONL))479+ /* same, not including its first digit (the qNaN/sNaN selector): */480+ #define ECONNANMASK ((0x01ffffff>>(32-6-DECECONL))<<(32-6-DECECONL))481+482+ /* Macros to decode the coefficient in a finite decFloat *df into */483+ /* a BCD string (uByte *bcdin) of length DECPMAX uBytes. */484+485+ /* In-line sequence to convert least significant 10 bits of uInt */486+ /* dpd to three BCD8 digits starting at uByte u. Note that an */487+ /* extra byte is written to the right of the three digits because */488+ /* four bytes are moved at a time for speed; the alternative */489+ /* macro moves exactly three bytes (usually slower). */490+ #define dpd2bcd8(u, dpd) memcpy(u, &DPD2BCD8[((dpd)&0x3ff)*4], 4)491+ #define dpd2bcd83(u, dpd) memcpy(u, &DPD2BCD8[((dpd)&0x3ff)*4], 3)492+493+ /* Decode the declets. After extracting each one, it is decoded */494+ /* to BCD8 using a table lookup (also used for variable-length */495+ /* decode). Each DPD decode is 3 bytes BCD8 plus a one-byte */496+ /* length which is not used, here). Fixed-length 4-byte moves */497+ /* are fast, however, almost everywhere, and so are used except */498+ /* for the final three bytes (to avoid overrun). The code below */499+ /* is 36 instructions for Doubles and about 70 for Quads, even */500+ /* on IA32. */501+502+ /* Two macros are defined for each format: */503+ /* GETCOEFF extracts the coefficient of the current format */504+ /* GETWCOEFF extracts the coefficient of the next-wider format. */505+ /* The latter is a copy of the next-wider GETCOEFF using DFWWORD. */506+507+ #if DECPMAX==7508+ #define GETCOEFF(df, bcd) { \509+ uInt sourhi=DFWORD(df, 0); \510+ *(bcd)=(uByte)DECCOMBMSD[sourhi>>26]; \511+ dpd2bcd8(bcd+1, sourhi>>10); \512+ dpd2bcd83(bcd+4, sourhi);}513+ #define GETWCOEFF(df, bcd) { \514+ uInt sourhi=DFWWORD(df, 0); \515+ uInt sourlo=DFWWORD(df, 1); \516+ *(bcd)=(uByte)DECCOMBMSD[sourhi>>26]; \517+ dpd2bcd8(bcd+1, sourhi>>8); \518+ dpd2bcd8(bcd+4, (sourhi<<2) | (sourlo>>30)); \519+ dpd2bcd8(bcd+7, sourlo>>20); \520+ dpd2bcd8(bcd+10, sourlo>>10); \521+ dpd2bcd83(bcd+13, sourlo);}522+523+ #elif DECPMAX==16524+ #define GETCOEFF(df, bcd) { \525+ uInt sourhi=DFWORD(df, 0); \526+ uInt sourlo=DFWORD(df, 1); \527+ *(bcd)=(uByte)DECCOMBMSD[sourhi>>26]; \528+ dpd2bcd8(bcd+1, sourhi>>8); \529+ dpd2bcd8(bcd+4, (sourhi<<2) | (sourlo>>30)); \530+ dpd2bcd8(bcd+7, sourlo>>20); \531+ dpd2bcd8(bcd+10, sourlo>>10); \532+ dpd2bcd83(bcd+13, sourlo);}533+ #define GETWCOEFF(df, bcd) { \534+ uInt sourhi=DFWWORD(df, 0); \535+ uInt sourmh=DFWWORD(df, 1); \536+ uInt sourml=DFWWORD(df, 2); \537+ uInt sourlo=DFWWORD(df, 3); \538+ *(bcd)=(uByte)DECCOMBMSD[sourhi>>26]; \539+ dpd2bcd8(bcd+1, sourhi>>4); \540+ dpd2bcd8(bcd+4, ((sourhi)<<6) | (sourmh>>26)); \541+ dpd2bcd8(bcd+7, sourmh>>16); \542+ dpd2bcd8(bcd+10, sourmh>>6); \543+ dpd2bcd8(bcd+13, ((sourmh)<<4) | (sourml>>28)); \544+ dpd2bcd8(bcd+16, sourml>>18); \545+ dpd2bcd8(bcd+19, sourml>>8); \546+ dpd2bcd8(bcd+22, ((sourml)<<2) | (sourlo>>30)); \547+ dpd2bcd8(bcd+25, sourlo>>20); \548+ dpd2bcd8(bcd+28, sourlo>>10); \549+ dpd2bcd83(bcd+31, sourlo);}550+551+ #elif DECPMAX==34552+ #define GETCOEFF(df, bcd) { \553+ uInt sourhi=DFWORD(df, 0); \554+ uInt sourmh=DFWORD(df, 1); \555+ uInt sourml=DFWORD(df, 2); \556+ uInt sourlo=DFWORD(df, 3); \557+ *(bcd)=(uByte)DECCOMBMSD[sourhi>>26]; \558+ dpd2bcd8(bcd+1, sourhi>>4); \559+ dpd2bcd8(bcd+4, ((sourhi)<<6) | (sourmh>>26)); \560+ dpd2bcd8(bcd+7, sourmh>>16); \561+ dpd2bcd8(bcd+10, sourmh>>6); \562+ dpd2bcd8(bcd+13, ((sourmh)<<4) | (sourml>>28)); \563+ dpd2bcd8(bcd+16, sourml>>18); \564+ dpd2bcd8(bcd+19, sourml>>8); \565+ dpd2bcd8(bcd+22, ((sourml)<<2) | (sourlo>>30)); \566+ dpd2bcd8(bcd+25, sourlo>>20); \567+ dpd2bcd8(bcd+28, sourlo>>10); \568+ dpd2bcd83(bcd+31, sourlo);}569+570+ #define GETWCOEFF(df, bcd) {??} /* [should never be used] */571+ #endif572+573+ /* Macros to decode the coefficient in a finite decFloat *df into */574+ /* a base-billion uInt array, with the least-significant */575+ /* 0-999999999 'digit' at offset 0. */576+577+ /* Decode the declets. After extracting each one, it is decoded */578+ /* to binary using a table lookup. Three tables are used; one */579+ /* the usual DPD to binary, the other two pre-multiplied by 1000 */580+ /* and 1000000 to avoid multiplication during decode. These */581+ /* tables can also be used for multiplying up the MSD as the DPD */582+ /* code for 0 through 9 is the identity. */583+ #define DPD2BIN0 DPD2BIN /* for prettier code */584+585+ #if DECPMAX==7586+ #define GETCOEFFBILL(df, buf) { \587+ uInt sourhi=DFWORD(df, 0); \588+ (buf)[0]=DPD2BIN0[sourhi&0x3ff] \589+ +DPD2BINK[(sourhi>>10)&0x3ff] \590+ +DPD2BINM[DECCOMBMSD[sourhi>>26]];}591+592+ #elif DECPMAX==16593+ #define GETCOEFFBILL(df, buf) { \594+ uInt sourhi, sourlo; \595+ sourlo=DFWORD(df, 1); \596+ (buf)[0]=DPD2BIN0[sourlo&0x3ff] \597+ +DPD2BINK[(sourlo>>10)&0x3ff] \598+ +DPD2BINM[(sourlo>>20)&0x3ff]; \599+ sourhi=DFWORD(df, 0); \600+ (buf)[1]=DPD2BIN0[((sourhi<<2) | (sourlo>>30))&0x3ff] \601+ +DPD2BINK[(sourhi>>8)&0x3ff] \602+ +DPD2BINM[DECCOMBMSD[sourhi>>26]];}603+604+ #elif DECPMAX==34605+ #define GETCOEFFBILL(df, buf) { \606+ uInt sourhi, sourmh, sourml, sourlo; \607+ sourlo=DFWORD(df, 3); \608+ (buf)[0]=DPD2BIN0[sourlo&0x3ff] \609+ +DPD2BINK[(sourlo>>10)&0x3ff] \610+ +DPD2BINM[(sourlo>>20)&0x3ff]; \611+ sourml=DFWORD(df, 2); \612+ (buf)[1]=DPD2BIN0[((sourml<<2) | (sourlo>>30))&0x3ff] \613+ +DPD2BINK[(sourml>>8)&0x3ff] \614+ +DPD2BINM[(sourml>>18)&0x3ff]; \615+ sourmh=DFWORD(df, 1); \616+ (buf)[2]=DPD2BIN0[((sourmh<<4) | (sourml>>28))&0x3ff] \617+ +DPD2BINK[(sourmh>>6)&0x3ff] \618+ +DPD2BINM[(sourmh>>16)&0x3ff]; \619+ sourhi=DFWORD(df, 0); \620+ (buf)[3]=DPD2BIN0[((sourhi<<6) | (sourmh>>26))&0x3ff] \621+ +DPD2BINK[(sourhi>>4)&0x3ff] \622+ +DPD2BINM[DECCOMBMSD[sourhi>>26]];}623+624+ #endif625+626+ /* Macros to decode the coefficient in a finite decFloat *df into */627+ /* a base-thousand uInt array (of size DECLETS+1, to allow for */628+ /* the MSD), with the least-significant 0-999 'digit' at offset 0.*/629+630+ /* Decode the declets. After extracting each one, it is decoded */631+ /* to binary using a table lookup. */632+ #if DECPMAX==7633+ #define GETCOEFFTHOU(df, buf) { \634+ uInt sourhi=DFWORD(df, 0); \635+ (buf)[0]=DPD2BIN[sourhi&0x3ff]; \636+ (buf)[1]=DPD2BIN[(sourhi>>10)&0x3ff]; \637+ (buf)[2]=DECCOMBMSD[sourhi>>26];}638+639+ #elif DECPMAX==16640+ #define GETCOEFFTHOU(df, buf) { \641+ uInt sourhi, sourlo; \642+ sourlo=DFWORD(df, 1); \643+ (buf)[0]=DPD2BIN[sourlo&0x3ff]; \644+ (buf)[1]=DPD2BIN[(sourlo>>10)&0x3ff]; \645+ (buf)[2]=DPD2BIN[(sourlo>>20)&0x3ff]; \646+ sourhi=DFWORD(df, 0); \647+ (buf)[3]=DPD2BIN[((sourhi<<2) | (sourlo>>30))&0x3ff]; \648+ (buf)[4]=DPD2BIN[(sourhi>>8)&0x3ff]; \649+ (buf)[5]=DECCOMBMSD[sourhi>>26];}650+651+ #elif DECPMAX==34652+ #define GETCOEFFTHOU(df, buf) { \653+ uInt sourhi, sourmh, sourml, sourlo; \654+ sourlo=DFWORD(df, 3); \655+ (buf)[0]=DPD2BIN[sourlo&0x3ff]; \656+ (buf)[1]=DPD2BIN[(sourlo>>10)&0x3ff]; \657+ (buf)[2]=DPD2BIN[(sourlo>>20)&0x3ff]; \658+ sourml=DFWORD(df, 2); \659+ (buf)[3]=DPD2BIN[((sourml<<2) | (sourlo>>30))&0x3ff]; \660+ (buf)[4]=DPD2BIN[(sourml>>8)&0x3ff]; \661+ (buf)[5]=DPD2BIN[(sourml>>18)&0x3ff]; \662+ sourmh=DFWORD(df, 1); \663+ (buf)[6]=DPD2BIN[((sourmh<<4) | (sourml>>28))&0x3ff]; \664+ (buf)[7]=DPD2BIN[(sourmh>>6)&0x3ff]; \665+ (buf)[8]=DPD2BIN[(sourmh>>16)&0x3ff]; \666+ sourhi=DFWORD(df, 0); \667+ (buf)[9]=DPD2BIN[((sourhi<<6) | (sourmh>>26))&0x3ff]; \668+ (buf)[10]=DPD2BIN[(sourhi>>4)&0x3ff]; \669+ (buf)[11]=DECCOMBMSD[sourhi>>26];}670+ #endif671+672+673+ /* Macros to decode the coefficient in a finite decFloat *df and */674+ /* add to a base-thousand uInt array (as for GETCOEFFTHOU). */675+ /* After the addition then most significant 'digit' in the array */676+ /* might have a value larger then 10 (with a maximum of 19). */677+ #if DECPMAX==7678+ #define ADDCOEFFTHOU(df, buf) { \679+ uInt sourhi=DFWORD(df, 0); \680+ (buf)[0]+=DPD2BIN[sourhi&0x3ff]; \681+ if (buf[0]>999) {buf[0]-=1000; buf[1]++;} \682+ (buf)[1]+=DPD2BIN[(sourhi>>10)&0x3ff]; \683+ if (buf[1]>999) {buf[1]-=1000; buf[2]++;} \684+ (buf)[2]+=DECCOMBMSD[sourhi>>26];}685+686+ #elif DECPMAX==16687+ #define ADDCOEFFTHOU(df, buf) { \688+ uInt sourhi, sourlo; \689+ sourlo=DFWORD(df, 1); \690+ (buf)[0]+=DPD2BIN[sourlo&0x3ff]; \691+ if (buf[0]>999) {buf[0]-=1000; buf[1]++;} \692+ (buf)[1]+=DPD2BIN[(sourlo>>10)&0x3ff]; \693+ if (buf[1]>999) {buf[1]-=1000; buf[2]++;} \694+ (buf)[2]+=DPD2BIN[(sourlo>>20)&0x3ff]; \695+ if (buf[2]>999) {buf[2]-=1000; buf[3]++;} \696+ sourhi=DFWORD(df, 0); \697+ (buf)[3]+=DPD2BIN[((sourhi<<2) | (sourlo>>30))&0x3ff]; \698+ if (buf[3]>999) {buf[3]-=1000; buf[4]++;} \699+ (buf)[4]+=DPD2BIN[(sourhi>>8)&0x3ff]; \700+ if (buf[4]>999) {buf[4]-=1000; buf[5]++;} \701+ (buf)[5]+=DECCOMBMSD[sourhi>>26];}702+703+ #elif DECPMAX==34704+ #define ADDCOEFFTHOU(df, buf) { \705+ uInt sourhi, sourmh, sourml, sourlo; \706+ sourlo=DFWORD(df, 3); \707+ (buf)[0]+=DPD2BIN[sourlo&0x3ff]; \708+ if (buf[0]>999) {buf[0]-=1000; buf[1]++;} \709+ (buf)[1]+=DPD2BIN[(sourlo>>10)&0x3ff]; \710+ if (buf[1]>999) {buf[1]-=1000; buf[2]++;} \711+ (buf)[2]+=DPD2BIN[(sourlo>>20)&0x3ff]; \712+ if (buf[2]>999) {buf[2]-=1000; buf[3]++;} \713+ sourml=DFWORD(df, 2); \714+ (buf)[3]+=DPD2BIN[((sourml<<2) | (sourlo>>30))&0x3ff]; \715+ if (buf[3]>999) {buf[3]-=1000; buf[4]++;} \716+ (buf)[4]+=DPD2BIN[(sourml>>8)&0x3ff]; \717+ if (buf[4]>999) {buf[4]-=1000; buf[5]++;} \718+ (buf)[5]+=DPD2BIN[(sourml>>18)&0x3ff]; \719+ if (buf[5]>999) {buf[5]-=1000; buf[6]++;} \720+ sourmh=DFWORD(df, 1); \721+ (buf)[6]+=DPD2BIN[((sourmh<<4) | (sourml>>28))&0x3ff]; \722+ if (buf[6]>999) {buf[6]-=1000; buf[7]++;} \723+ (buf)[7]+=DPD2BIN[(sourmh>>6)&0x3ff]; \724+ if (buf[7]>999) {buf[7]-=1000; buf[8]++;} \725+ (buf)[8]+=DPD2BIN[(sourmh>>16)&0x3ff]; \726+ if (buf[8]>999) {buf[8]-=1000; buf[9]++;} \727+ sourhi=DFWORD(df, 0); \728+ (buf)[9]+=DPD2BIN[((sourhi<<6) | (sourmh>>26))&0x3ff]; \729+ if (buf[9]>999) {buf[9]-=1000; buf[10]++;} \730+ (buf)[10]+=DPD2BIN[(sourhi>>4)&0x3ff]; \731+ if (buf[10]>999) {buf[10]-=1000; buf[11]++;} \732+ (buf)[11]+=DECCOMBMSD[sourhi>>26];}733+ #endif734+735+736+ /* Set a decFloat to the maximum positive finite number (Nmax) */737+ #if DECPMAX==7738+ #define DFSETNMAX(df) \739+ {DFWORD(df, 0)=0x77f3fcff;}740+ #elif DECPMAX==16741+ #define DFSETNMAX(df) \742+ {DFWORD(df, 0)=0x77fcff3f; \743+ DFWORD(df, 1)=0xcff3fcff;}744+ #elif DECPMAX==34745+ #define DFSETNMAX(df) \746+ {DFWORD(df, 0)=0x77ffcff3; \747+ DFWORD(df, 1)=0xfcff3fcf; \748+ DFWORD(df, 2)=0xf3fcff3f; \749+ DFWORD(df, 3)=0xcff3fcff;}750+ #endif751+752+ /* [end of format-dependent macros and constants] */753+ #endif754+755+#else756+ #error decNumberLocal included more than once757+#endifadded:src/decNumber/decPacked.c+220 added
1+/* ------------------------------------------------------------------ */2+/* Packed Decimal conversion module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2002. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises the routines for Packed Decimal format */20+/* numbers. Conversions are supplied to and from decNumber, which in */21+/* turn supports: */22+/* conversions to and from string */23+/* arithmetic routines */24+/* utilities. */25+/* Conversions from decNumber to and from densely packed decimal */26+/* formats are provided by the decimal32 through decimal128 modules. */27+/* ------------------------------------------------------------------ */28+29+#include <string.h> // for NULL30+#include "decNumber.h" // base number library31+#include "decPacked.h" // packed decimal32+#include "decNumberLocal.h" // decNumber local types, etc.33+34+/* ------------------------------------------------------------------ */35+/* decPackedFromNumber -- convert decNumber to BCD Packed Decimal */36+/* */37+/* bcd is the BCD bytes */38+/* length is the length of the BCD array */39+/* scale is the scale result */40+/* dn is the decNumber */41+/* returns bcd, or NULL if error */42+/* */43+/* The number is converted to a BCD packed decimal byte array, */44+/* right aligned in the bcd array, whose length is indicated by the */45+/* second parameter. The final 4-bit nibble in the array will be a */46+/* sign nibble, C (1100) for + and D (1101) for -. Unused bytes and */47+/* nibbles to the left of the number are set to 0. */48+/* */49+/* scale is set to the scale of the number (this is the exponent, */50+/* negated). To force the number to a specified scale, first use the */51+/* decNumberRescale routine, which will round and change the exponent */52+/* as necessary. */53+/* */54+/* If there is an error (that is, the decNumber has too many digits */55+/* to fit in length bytes, or it is a NaN or Infinity), NULL is */56+/* returned and the bcd and scale results are unchanged. Otherwise */57+/* bcd is returned. */58+/* ------------------------------------------------------------------ */59+uByte * decPackedFromNumber(uByte *bcd, Int length, Int *scale,60+ const decNumber *dn) {61+ const Unit *up=dn->lsu; // Unit array pointer62+ uByte obyte, *out; // current output byte, and where it goes63+ Int indigs=dn->digits; // digits processed64+ uInt cut=DECDPUN; // downcounter per Unit65+ uInt u=*up; // work66+ uInt nib; // ..67+ #if DECDPUN<=468+ uInt temp; // ..69+ #endif70+71+ if (dn->digits>length*2-1 // too long ..72+ ||(dn->bits & DECSPECIAL)) return NULL; // .. or special -- hopeless73+74+ if (dn->bits&DECNEG) obyte=DECPMINUS; // set the sign ..75+ else obyte=DECPPLUS;76+ *scale=-dn->exponent; // .. and scale77+78+ // loop from lowest (rightmost) byte79+ out=bcd+length-1; // -> final byte80+ for (; out>=bcd; out--) {81+ if (indigs>0) {82+ if (cut==0) {83+ up++;84+ u=*up;85+ cut=DECDPUN;86+ }87+ #if DECDPUN<=488+ temp=(u*6554)>>16; // fast /1089+ nib=u-X10(temp);90+ u=temp;91+ #else92+ nib=u%10; // cannot use *6554 trick :-(93+ u=u/10;94+ #endif95+ obyte|=(nib<<4);96+ indigs--;97+ cut--;98+ }99+ *out=obyte;100+ obyte=0; // assume 0101+ if (indigs>0) {102+ if (cut==0) {103+ up++;104+ u=*up;105+ cut=DECDPUN;106+ }107+ #if DECDPUN<=4108+ temp=(u*6554)>>16; // as above109+ obyte=(uByte)(u-X10(temp));110+ u=temp;111+ #else112+ obyte=(uByte)(u%10);113+ u=u/10;114+ #endif115+ indigs--;116+ cut--;117+ }118+ } // loop119+120+ return bcd;121+ } // decPackedFromNumber122+123+/* ------------------------------------------------------------------ */124+/* decPackedToNumber -- convert BCD Packed Decimal to a decNumber */125+/* */126+/* bcd is the BCD bytes */127+/* length is the length of the BCD array */128+/* scale is the scale associated with the BCD integer */129+/* dn is the decNumber [with space for length*2 digits] */130+/* returns dn, or NULL if error */131+/* */132+/* The BCD packed decimal byte array, together with an associated */133+/* scale, is converted to a decNumber. The BCD array is assumed full */134+/* of digits, and must be ended by a 4-bit sign nibble in the least */135+/* significant four bits of the final byte. */136+/* */137+/* The scale is used (negated) as the exponent of the decNumber. */138+/* Note that zeros may have a sign and/or a scale. */139+/* */140+/* The decNumber structure is assumed to have sufficient space to */141+/* hold the converted number (that is, up to length*2-1 digits), so */142+/* no error is possible unless the adjusted exponent is out of range, */143+/* no sign nibble was found, or a sign nibble was found before the */144+/* final nibble. In these error cases, NULL is returned and the */145+/* decNumber will be 0. */146+/* ------------------------------------------------------------------ */147+decNumber * decPackedToNumber(const uByte *bcd, Int length,148+ const Int *scale, decNumber *dn) {149+ const uByte *last=bcd+length-1; // -> last byte150+ const uByte *first; // -> first non-zero byte151+ uInt nib; // work nibble152+ Unit *up=dn->lsu; // output pointer153+ Int digits; // digits count154+ Int cut=0; // phase of output155+156+ decNumberZero(dn); // default result157+ last=&bcd[length-1];158+ nib=*last & 0x0f; // get the sign159+ if (nib==DECPMINUS || nib==DECPMINUSALT) dn->bits=DECNEG;160+ else if (nib<=9) return NULL; // not a sign nibble161+162+ // skip leading zero bytes [final byte is always non-zero, due to sign]163+ for (first=bcd; *first==0;) first++;164+ digits=(last-first)*2+1; // calculate digits ..165+ if ((*first & 0xf0)==0) digits--; // adjust for leading zero nibble166+ if (digits!=0) dn->digits=digits; // count of actual digits [if 0,167+ // leave as 1]168+169+ // check the adjusted exponent; note that scale could be unbounded170+ dn->exponent=-*scale; // set the exponent171+ if (*scale>=0) { // usual case172+ if ((dn->digits-*scale-1)<-DECNUMMAXE) { // underflow173+ decNumberZero(dn);174+ return NULL;}175+ }176+ else { // -ve scale; +ve exponent177+ // need to be careful to avoid wrap, here, also BADINT case178+ if ((*scale<-DECNUMMAXE) // overflow even without digits179+ || ((dn->digits-*scale-1)>DECNUMMAXE)) { // overflow180+ decNumberZero(dn);181+ return NULL;}182+ }183+ if (digits==0) return dn; // result was zero184+185+ // copy the digits to the number's units, starting at the lsu186+ // [unrolled]187+ for (;;) { // forever188+ // left nibble first189+ nib=(unsigned)(*last & 0xf0)>>4;190+ // got a digit, in nib191+ if (nib>9) {decNumberZero(dn); return NULL;}192+193+ if (cut==0) *up=(Unit)nib;194+ else *up=(Unit)(*up+nib*DECPOWERS[cut]);195+ digits--;196+ if (digits==0) break; // got them all197+ cut++;198+ if (cut==DECDPUN) {199+ up++;200+ cut=0;201+ }202+ last--; // ready for next203+ nib=*last & 0x0f; // get right nibble204+ if (nib>9) {decNumberZero(dn); return NULL;}205+206+ // got a digit, in nib207+ if (cut==0) *up=(Unit)nib;208+ else *up=(Unit)(*up+nib*DECPOWERS[cut]);209+ digits--;210+ if (digits==0) break; // got them all211+ cut++;212+ if (cut==DECDPUN) {213+ up++;214+ cut=0;215+ }216+ } // forever217+218+ return dn;219+ } // decPackedToNumber220+added:src/decNumber/decPacked.h+52 added
1+/* ------------------------------------------------------------------ */2+/* Packed Decimal conversion module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2005. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is called decNumber.pdf. This document is */11+/* available, together with arithmetic and format specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECPACKED)21+ #define DECPACKED22+ #define DECPNAME "decPacked" /* Short name */23+ #define DECPFULLNAME "Packed Decimal conversions" /* Verbose name */24+ #define DECPAUTHOR "Mike Cowlishaw" /* Who to blame */25+26+ #define DECPACKED_DefP 32 /* default precision */27+28+ #ifndef DECNUMDIGITS29+ #define DECNUMDIGITS DECPACKED_DefP /* size if not already defined*/30+ #endif31+ #include "decNumber.h" /* context and number library */32+33+ /* Sign nibble constants */34+ #if !defined(DECPPLUSALT)35+ #define DECPPLUSALT 0x0A /* alternate plus nibble */36+ #define DECPMINUSALT 0x0B /* alternate minus nibble */37+ #define DECPPLUS 0x0C /* preferred plus nibble */38+ #define DECPMINUS 0x0D /* preferred minus nibble */39+ #define DECPPLUSALT2 0x0E /* alternate plus nibble */40+ #define DECPUNSIGNED 0x0F /* alternate plus nibble (unsigned) */41+ #endif42+43+ /* ---------------------------------------------------------------- */44+ /* decPacked public routines */45+ /* ---------------------------------------------------------------- */46+ /* Conversions */47+ uint8_t * decPackedFromNumber(uint8_t *, int32_t, int32_t *,48+ const decNumber *);49+ decNumber * decPackedToNumber(const uint8_t *, int32_t, const int32_t *,50+ decNumber *);51+52+#endifadded:src/decNumber/decQuad.c+135 added
1+/* ------------------------------------------------------------------ */2+/* decQuad.c -- decQuad operations module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises decQuad operations (including conversions) */20+/* ------------------------------------------------------------------ */21+22+23+/* Constant mappings for shared code */24+#define DECPMAX DECQUAD_Pmax25+#define DECEMIN DECQUAD_Emin26+#define DECEMAX DECQUAD_Emax27+#define DECEMAXD DECQUAD_EmaxD28+#define DECBYTES DECQUAD_Bytes29+#define DECSTRING DECQUAD_String30+#define DECECONL DECQUAD_EconL31+#define DECBIAS DECQUAD_Bias32+#define DECLETS DECQUAD_Declets33+#define DECQTINY (-DECQUAD_Bias)34+35+/* Type and function mappings for shared code */36+#define decFloat decQuad // Type name37+38+// Utilities and conversions (binary results, extractors, etc.)39+#define decFloatFromBCD decQuadFromBCD40+#define decFloatFromInt32 decQuadFromInt3241+#define decFloatFromPacked decQuadFromPacked42+#define decFloatFromPackedChecked decQuadFromPackedChecked43+#define decFloatFromString decQuadFromString44+#define decFloatFromUInt32 decQuadFromUInt3245+#define decFloatFromWider decQuadFromWider46+#define decFloatGetCoefficient decQuadGetCoefficient47+#define decFloatGetExponent decQuadGetExponent48+#define decFloatSetCoefficient decQuadSetCoefficient49+#define decFloatSetExponent decQuadSetExponent50+#define decFloatShow decQuadShow51+#define decFloatToBCD decQuadToBCD52+#define decFloatToEngString decQuadToEngString53+#define decFloatToInt32 decQuadToInt3254+#define decFloatToInt32Exact decQuadToInt32Exact55+#define decFloatToPacked decQuadToPacked56+#define decFloatToString decQuadToString57+#define decFloatToUInt32 decQuadToUInt3258+#define decFloatToUInt32Exact decQuadToUInt32Exact59+#define decFloatToWider decQuadToWider60+#define decFloatZero decQuadZero61+62+// Computational (result is a decFloat)63+#define decFloatAbs decQuadAbs64+#define decFloatAdd decQuadAdd65+#define decFloatAnd decQuadAnd66+#define decFloatDivide decQuadDivide67+#define decFloatDivideInteger decQuadDivideInteger68+#define decFloatFMA decQuadFMA69+#define decFloatInvert decQuadInvert70+#define decFloatLogB decQuadLogB71+#define decFloatMax decQuadMax72+#define decFloatMaxMag decQuadMaxMag73+#define decFloatMin decQuadMin74+#define decFloatMinMag decQuadMinMag75+#define decFloatMinus decQuadMinus76+#define decFloatMultiply decQuadMultiply77+#define decFloatNextMinus decQuadNextMinus78+#define decFloatNextPlus decQuadNextPlus79+#define decFloatNextToward decQuadNextToward80+#define decFloatOr decQuadOr81+#define decFloatPlus decQuadPlus82+#define decFloatQuantize decQuadQuantize83+#define decFloatReduce decQuadReduce84+#define decFloatRemainder decQuadRemainder85+#define decFloatRemainderNear decQuadRemainderNear86+#define decFloatRotate decQuadRotate87+#define decFloatScaleB decQuadScaleB88+#define decFloatShift decQuadShift89+#define decFloatSubtract decQuadSubtract90+#define decFloatToIntegralValue decQuadToIntegralValue91+#define decFloatToIntegralExact decQuadToIntegralExact92+#define decFloatXor decQuadXor93+94+// Comparisons95+#define decFloatCompare decQuadCompare96+#define decFloatCompareSignal decQuadCompareSignal97+#define decFloatCompareTotal decQuadCompareTotal98+#define decFloatCompareTotalMag decQuadCompareTotalMag99+100+// Copies101+#define decFloatCanonical decQuadCanonical102+#define decFloatCopy decQuadCopy103+#define decFloatCopyAbs decQuadCopyAbs104+#define decFloatCopyNegate decQuadCopyNegate105+#define decFloatCopySign decQuadCopySign106+107+// Non-computational108+#define decFloatClass decQuadClass109+#define decFloatClassString decQuadClassString110+#define decFloatDigits decQuadDigits111+#define decFloatIsCanonical decQuadIsCanonical112+#define decFloatIsFinite decQuadIsFinite113+#define decFloatIsInfinite decQuadIsInfinite114+#define decFloatIsInteger decQuadIsInteger115+#define decFloatIsLogical decQuadIsLogical116+#define decFloatIsNaN decQuadIsNaN117+#define decFloatIsNegative decQuadIsNegative118+#define decFloatIsNormal decQuadIsNormal119+#define decFloatIsPositive decQuadIsPositive120+#define decFloatIsSignaling decQuadIsSignaling121+#define decFloatIsSignalling decQuadIsSignalling122+#define decFloatIsSigned decQuadIsSigned123+#define decFloatIsSubnormal decQuadIsSubnormal124+#define decFloatIsZero decQuadIsZero125+#define decFloatRadix decQuadRadix126+#define decFloatSameQuantum decQuadSameQuantum127+#define decFloatVersion decQuadVersion128+129+/* And now the code itself */130+#include "decContext.h" // public includes131+#include "decQuad.h" // ..132+#include "decNumberLocal.h" // local includes (need DECPMAX)133+#include "decCommon.c" // non-arithmetic decFloat routines134+#include "decBasic.c" // basic formats routines135+added:src/decNumber/decQuad.h+177 added
1+/* ------------------------------------------------------------------ */2+/* decQuad.h -- Decimal 128-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2010. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This include file is always included by decSingle and decDouble, */20+/* and therefore also holds useful constants used by all three. */21+22+#if !defined(DECQUAD)23+ #define DECQUAD24+25+ #define DECQUADNAME "decimalQuad" /* Short name */26+ #define DECQUADTITLE "Decimal 128-bit datum" /* Verbose name */27+ #define DECQUADAUTHOR "Mike Cowlishaw" /* Who to blame */28+29+ /* parameters for decQuads */30+ #define DECQUAD_Bytes 16 /* length */31+ #define DECQUAD_Pmax 34 /* maximum precision (digits) */32+ #define DECQUAD_Emin -6143 /* minimum adjusted exponent */33+ #define DECQUAD_Emax 6144 /* maximum adjusted exponent */34+ #define DECQUAD_EmaxD 4 /* maximum exponent digits */35+ #define DECQUAD_Bias 6176 /* bias for the exponent */36+ #define DECQUAD_String 43 /* maximum string length, +1 */37+ #define DECQUAD_EconL 12 /* exponent continuation length */38+ #define DECQUAD_Declets 11 /* count of declets */39+ /* highest biased exponent (Elimit-1) */40+ #define DECQUAD_Ehigh (DECQUAD_Emax + DECQUAD_Bias - (DECQUAD_Pmax-1))41+42+ /* Required include */43+ #include "decContext.h"44+45+ /* The decQuad decimal 128-bit type, accessible by all sizes */46+ typedef union {47+ uint8_t bytes[DECQUAD_Bytes]; /* fields: 1, 5, 12, 110 bits */48+ uint16_t shorts[DECQUAD_Bytes/2];49+ uint32_t words[DECQUAD_Bytes/4];50+ #if DECUSE6451+ uint64_t longs[DECQUAD_Bytes/8];52+ #endif53+ } decQuad;54+55+ /* ---------------------------------------------------------------- */56+ /* Shared constants */57+ /* ---------------------------------------------------------------- */58+59+ /* sign and special values [top 32-bits; last two bits are don't-care60+ for Infinity on input, last bit don't-care for NaNs] */61+ #define DECFLOAT_Sign 0x80000000 /* 1 00000 00 Sign */62+ #define DECFLOAT_NaN 0x7c000000 /* 0 11111 00 NaN generic */63+ #define DECFLOAT_qNaN 0x7c000000 /* 0 11111 00 qNaN */64+ #define DECFLOAT_sNaN 0x7e000000 /* 0 11111 10 sNaN */65+ #define DECFLOAT_Inf 0x78000000 /* 0 11110 00 Infinity */66+ #define DECFLOAT_MinSp 0x78000000 /* minimum special value */67+ /* [specials are all >=MinSp] */68+ /* Sign nibble constants */69+ #if !defined(DECPPLUSALT)70+ #define DECPPLUSALT 0x0A /* alternate plus nibble */71+ #define DECPMINUSALT 0x0B /* alternate minus nibble */72+ #define DECPPLUS 0x0C /* preferred plus nibble */73+ #define DECPMINUS 0x0D /* preferred minus nibble */74+ #define DECPPLUSALT2 0x0E /* alternate plus nibble */75+ #define DECPUNSIGNED 0x0F /* alternate plus nibble (unsigned) */76+ #endif77+78+ /* ---------------------------------------------------------------- */79+ /* Routines -- implemented as decFloat routines in common files */80+ /* ---------------------------------------------------------------- */81+82+ /* Utilities and conversions, extractors, etc.) */83+ extern decQuad * decQuadFromBCD(decQuad *, int32_t, const uint8_t *, int32_t);84+ extern decQuad * decQuadFromInt32(decQuad *, int32_t);85+ extern decQuad * decQuadFromPacked(decQuad *, int32_t, const uint8_t *);86+ extern decQuad * decQuadFromPackedChecked(decQuad *, int32_t, const uint8_t *);87+ extern decQuad * decQuadFromString(decQuad *, const char *, decContext *);88+ extern decQuad * decQuadFromUInt32(decQuad *, uint32_t);89+ extern int32_t decQuadGetCoefficient(const decQuad *, uint8_t *);90+ extern int32_t decQuadGetExponent(const decQuad *);91+ extern decQuad * decQuadSetCoefficient(decQuad *, const uint8_t *, int32_t);92+ extern decQuad * decQuadSetExponent(decQuad *, decContext *, int32_t);93+ extern void decQuadShow(const decQuad *, const char *);94+ extern int32_t decQuadToBCD(const decQuad *, int32_t *, uint8_t *);95+ extern char * decQuadToEngString(const decQuad *, char *);96+ extern int32_t decQuadToInt32(const decQuad *, decContext *, enum rounding);97+ extern int32_t decQuadToInt32Exact(const decQuad *, decContext *, enum rounding);98+ extern int32_t decQuadToPacked(const decQuad *, int32_t *, uint8_t *);99+ extern char * decQuadToString(const decQuad *, char *);100+ extern uint32_t decQuadToUInt32(const decQuad *, decContext *, enum rounding);101+ extern uint32_t decQuadToUInt32Exact(const decQuad *, decContext *, enum rounding);102+ extern decQuad * decQuadZero(decQuad *);103+104+ /* Computational (result is a decQuad) */105+ extern decQuad * decQuadAbs(decQuad *, const decQuad *, decContext *);106+ extern decQuad * decQuadAdd(decQuad *, const decQuad *, const decQuad *, decContext *);107+ extern decQuad * decQuadAnd(decQuad *, const decQuad *, const decQuad *, decContext *);108+ extern decQuad * decQuadDivide(decQuad *, const decQuad *, const decQuad *, decContext *);109+ extern decQuad * decQuadDivideInteger(decQuad *, const decQuad *, const decQuad *, decContext *);110+ extern decQuad * decQuadFMA(decQuad *, const decQuad *, const decQuad *, const decQuad *, decContext *);111+ extern decQuad * decQuadInvert(decQuad *, const decQuad *, decContext *);112+ extern decQuad * decQuadLogB(decQuad *, const decQuad *, decContext *);113+ extern decQuad * decQuadMax(decQuad *, const decQuad *, const decQuad *, decContext *);114+ extern decQuad * decQuadMaxMag(decQuad *, const decQuad *, const decQuad *, decContext *);115+ extern decQuad * decQuadMin(decQuad *, const decQuad *, const decQuad *, decContext *);116+ extern decQuad * decQuadMinMag(decQuad *, const decQuad *, const decQuad *, decContext *);117+ extern decQuad * decQuadMinus(decQuad *, const decQuad *, decContext *);118+ extern decQuad * decQuadMultiply(decQuad *, const decQuad *, const decQuad *, decContext *);119+ extern decQuad * decQuadNextMinus(decQuad *, const decQuad *, decContext *);120+ extern decQuad * decQuadNextPlus(decQuad *, const decQuad *, decContext *);121+ extern decQuad * decQuadNextToward(decQuad *, const decQuad *, const decQuad *, decContext *);122+ extern decQuad * decQuadOr(decQuad *, const decQuad *, const decQuad *, decContext *);123+ extern decQuad * decQuadPlus(decQuad *, const decQuad *, decContext *);124+ extern decQuad * decQuadQuantize(decQuad *, const decQuad *, const decQuad *, decContext *);125+ extern decQuad * decQuadReduce(decQuad *, const decQuad *, decContext *);126+ extern decQuad * decQuadRemainder(decQuad *, const decQuad *, const decQuad *, decContext *);127+ extern decQuad * decQuadRemainderNear(decQuad *, const decQuad *, const decQuad *, decContext *);128+ extern decQuad * decQuadRotate(decQuad *, const decQuad *, const decQuad *, decContext *);129+ extern decQuad * decQuadScaleB(decQuad *, const decQuad *, const decQuad *, decContext *);130+ extern decQuad * decQuadShift(decQuad *, const decQuad *, const decQuad *, decContext *);131+ extern decQuad * decQuadSubtract(decQuad *, const decQuad *, const decQuad *, decContext *);132+ extern decQuad * decQuadToIntegralValue(decQuad *, const decQuad *, decContext *, enum rounding);133+ extern decQuad * decQuadToIntegralExact(decQuad *, const decQuad *, decContext *);134+ extern decQuad * decQuadXor(decQuad *, const decQuad *, const decQuad *, decContext *);135+136+ /* Comparisons */137+ extern decQuad * decQuadCompare(decQuad *, const decQuad *, const decQuad *, decContext *);138+ extern decQuad * decQuadCompareSignal(decQuad *, const decQuad *, const decQuad *, decContext *);139+ extern decQuad * decQuadCompareTotal(decQuad *, const decQuad *, const decQuad *);140+ extern decQuad * decQuadCompareTotalMag(decQuad *, const decQuad *, const decQuad *);141+142+ /* Copies */143+ extern decQuad * decQuadCanonical(decQuad *, const decQuad *);144+ extern decQuad * decQuadCopy(decQuad *, const decQuad *);145+ extern decQuad * decQuadCopyAbs(decQuad *, const decQuad *);146+ extern decQuad * decQuadCopyNegate(decQuad *, const decQuad *);147+ extern decQuad * decQuadCopySign(decQuad *, const decQuad *, const decQuad *);148+149+ /* Non-computational */150+ extern enum decClass decQuadClass(const decQuad *);151+ extern const char * decQuadClassString(const decQuad *);152+ extern uint32_t decQuadDigits(const decQuad *);153+ extern uint32_t decQuadIsCanonical(const decQuad *);154+ extern uint32_t decQuadIsFinite(const decQuad *);155+ extern uint32_t decQuadIsInteger(const decQuad *);156+ extern uint32_t decQuadIsLogical(const decQuad *);157+ extern uint32_t decQuadIsInfinite(const decQuad *);158+ extern uint32_t decQuadIsNaN(const decQuad *);159+ extern uint32_t decQuadIsNegative(const decQuad *);160+ extern uint32_t decQuadIsNormal(const decQuad *);161+ extern uint32_t decQuadIsPositive(const decQuad *);162+ extern uint32_t decQuadIsSignaling(const decQuad *);163+ extern uint32_t decQuadIsSignalling(const decQuad *);164+ extern uint32_t decQuadIsSigned(const decQuad *);165+ extern uint32_t decQuadIsSubnormal(const decQuad *);166+ extern uint32_t decQuadIsZero(const decQuad *);167+ extern uint32_t decQuadRadix(const decQuad *);168+ extern uint32_t decQuadSameQuantum(const decQuad *, const decQuad *);169+ extern const char * decQuadVersion(void);170+171+ /* decNumber conversions; these are implemented as macros so as not */172+ /* to force a dependency on decimal128 and decNumber in decQuad. */173+ /* decQuadFromNumber returns a decimal128 * to avoid warnings. */174+ #define decQuadToNumber(dq, dn) decimal128ToNumber((decimal128 *)(dq), dn)175+ #define decQuadFromNumber(dq, dn, set) decimal128FromNumber((decimal128 *)(dq), dn, set)176+177+#endifadded:src/decNumber/decSingle.c+71 added
1+/* ------------------------------------------------------------------ */2+/* decSingle.c -- decSingle operations module */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+/* This module comprises decSingle operations (including conversions) */20+/* ------------------------------------------------------------------ */21+22+#include "decContext.h" // public includes23+#include "decSingle.h" // public includes24+25+/* Constant mappings for shared code */26+#define DECPMAX DECSINGLE_Pmax27+#define DECEMIN DECSINGLE_Emin28+#define DECEMAX DECSINGLE_Emax29+#define DECEMAXD DECSINGLE_EmaxD30+#define DECBYTES DECSINGLE_Bytes31+#define DECSTRING DECSINGLE_String32+#define DECECONL DECSINGLE_EconL33+#define DECBIAS DECSINGLE_Bias34+#define DECLETS DECSINGLE_Declets35+#define DECQTINY (-DECSINGLE_Bias)36+// parameters of next-wider format37+#define DECWBYTES DECDOUBLE_Bytes38+#define DECWPMAX DECDOUBLE_Pmax39+#define DECWECONL DECDOUBLE_EconL40+#define DECWBIAS DECDOUBLE_Bias41+42+/* Type and function mappings for shared code */43+#define decFloat decSingle // Type name44+#define decFloatWider decDouble // Type name45+46+// Utility (binary results, extractors, etc.)47+#define decFloatFromBCD decSingleFromBCD48+#define decFloatFromPacked decSingleFromPacked49+#define decFloatFromPackedChecked decSingleFromPackedChecked50+#define decFloatFromString decSingleFromString51+#define decFloatFromWider decSingleFromWider52+#define decFloatGetCoefficient decSingleGetCoefficient53+#define decFloatGetExponent decSingleGetExponent54+#define decFloatSetCoefficient decSingleSetCoefficient55+#define decFloatSetExponent decSingleSetExponent56+#define decFloatShow decSingleShow57+#define decFloatToBCD decSingleToBCD58+#define decFloatToEngString decSingleToEngString59+#define decFloatToPacked decSingleToPacked60+#define decFloatToString decSingleToString61+#define decFloatToWider decSingleToWider62+#define decFloatZero decSingleZero63+64+// Non-computational65+#define decFloatRadix decSingleRadix66+#define decFloatVersion decSingleVersion67+68+#include "decNumberLocal.h" // local includes (need DECPMAX)69+#include "decCommon.c" // non-basic decFloat routines70+// [Do not include decBasic.c for decimal32]71+added:src/decNumber/decSingle.h+86 added
1+/* ------------------------------------------------------------------ */2+/* decSingle.h -- Decimal 32-bit format module header */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */5+/* */6+/* This software is made available under the terms of the */7+/* ICU License -- ICU 1.8.1 and later. */8+/* */9+/* The description and User's Guide ("The decNumber C Library") for */10+/* this software is included in the package as decNumber.pdf. This */11+/* document is also available in HTML, together with specifications, */12+/* testcases, and Web links, on the General Decimal Arithmetic page. */13+/* */14+/* Please send comments, suggestions, and corrections to the author: */15+/* mfc@uk.ibm.com */16+/* Mike Cowlishaw, IBM Fellow */17+/* IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK */18+/* ------------------------------------------------------------------ */19+20+#if !defined(DECSINGLE)21+ #define DECSINGLE22+23+ #define DECSINGLENAME "decSingle" /* Short name */24+ #define DECSINGLETITLE "Decimal 32-bit datum" /* Verbose name */25+ #define DECSINGLEAUTHOR "Mike Cowlishaw" /* Who to blame */26+27+ /* parameters for decSingles */28+ #define DECSINGLE_Bytes 4 /* length */29+ #define DECSINGLE_Pmax 7 /* maximum precision (digits) */30+ #define DECSINGLE_Emin -95 /* minimum adjusted exponent */31+ #define DECSINGLE_Emax 96 /* maximum adjusted exponent */32+ #define DECSINGLE_EmaxD 3 /* maximum exponent digits */33+ #define DECSINGLE_Bias 101 /* bias for the exponent */34+ #define DECSINGLE_String 16 /* maximum string length, +1 */35+ #define DECSINGLE_EconL 6 /* exponent continuation length */36+ #define DECSINGLE_Declets 2 /* count of declets */37+ /* highest biased exponent (Elimit-1) */38+ #define DECSINGLE_Ehigh (DECSINGLE_Emax + DECSINGLE_Bias - (DECSINGLE_Pmax-1))39+40+ /* Required includes */41+ #include "decContext.h"42+ #include "decQuad.h"43+ #include "decDouble.h"44+45+ /* The decSingle decimal 32-bit type, accessible by all sizes */46+ typedef union {47+ uint8_t bytes[DECSINGLE_Bytes]; /* fields: 1, 5, 6, 20 bits */48+ uint16_t shorts[DECSINGLE_Bytes/2];49+ uint32_t words[DECSINGLE_Bytes/4];50+ } decSingle;51+52+ /* ---------------------------------------------------------------- */53+ /* Routines -- implemented as decFloat routines in common files */54+ /* ---------------------------------------------------------------- */55+56+ /* Utilities (binary argument(s) or result, extractors, etc.) */57+ extern decSingle * decSingleFromBCD(decSingle *, int32_t, const uint8_t *, int32_t);58+ extern decSingle * decSingleFromPacked(decSingle *, int32_t, const uint8_t *);59+ extern decSingle * decSingleFromPackedChecked(decSingle *, int32_t, const uint8_t *);60+ extern decSingle * decSingleFromString(decSingle *, const char *, decContext *);61+ extern decSingle * decSingleFromWider(decSingle *, const decDouble *, decContext *);62+ extern int32_t decSingleGetCoefficient(const decSingle *, uint8_t *);63+ extern int32_t decSingleGetExponent(const decSingle *);64+ extern decSingle * decSingleSetCoefficient(decSingle *, const uint8_t *, int32_t);65+ extern decSingle * decSingleSetExponent(decSingle *, decContext *, int32_t);66+ extern void decSingleShow(const decSingle *, const char *);67+ extern int32_t decSingleToBCD(const decSingle *, int32_t *, uint8_t *);68+ extern char * decSingleToEngString(const decSingle *, char *);69+ extern int32_t decSingleToPacked(const decSingle *, int32_t *, uint8_t *);70+ extern char * decSingleToString(const decSingle *, char *);71+ extern decDouble * decSingleToWider(const decSingle *, decDouble *);72+ extern decSingle * decSingleZero(decSingle *);73+74+ /* (No Arithmetic routines for decSingle) */75+76+ /* Non-computational */77+ extern uint32_t decSingleRadix(const decSingle *);78+ extern const char * decSingleVersion(void);79+80+ /* decNumber conversions; these are implemented as macros so as not */81+ /* to force a dependency on decimal32 and decNumber in decSingle. */82+ /* decSingleFromNumber returns a decimal32 * to avoid warnings. */83+ #define decSingleToNumber(dq, dn) decimal32ToNumber((decimal32 *)(dq), dn)84+ #define decSingleFromNumber(dq, dn, set) decimal32FromNumber((decimal32 *)(dq), dn, set)85+86+#endifadded:src/decNumber/example1.c+38 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example1.c -- convert the first two argument words to decNumber,9+// add them together, and display the result10+11+#define DECNUMDIGITS 34 // work with up to 34 digits12+#include "decNumber.h" // base number library13+#include <stdio.h> // for printf14+15+int main(int argc, char *argv[]) {16+ decNumber a, b; // working numbers17+ decContext set; // working context18+ char string[DECNUMDIGITS+14]; // conversion buffer19+20+ decContextTestEndian(0); // warn if DECLITEND is wrong21+22+ if (argc<3) { // not enough words23+ printf("Please supply two numbers to add.\n");24+ return 1;25+ }26+ decContextDefault(&set, DEC_INIT_BASE); // initialize27+ set.traps=0; // no traps, thank you28+ set.digits=DECNUMDIGITS; // set precision29+30+ decNumberFromString(&a, argv[1], &set);31+ decNumberFromString(&b, argv[2], &set);32+33+ decNumberAdd(&a, &a, &b, &set); // a=a+b34+ decNumberToString(&a, string);35+36+ printf("%s + %s => %s\n", argv[1], argv[2], string);37+ return 0;38+ } // mainadded:src/decNumber/example2.c+52 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example2.c -- calculate compound interest9+// Arguments are investment, rate (%), and years10+11+#define DECNUMDIGITS 38 // work with up to 38 digits12+#include "decNumber.h" // base number library13+#include <stdio.h> // for printf14+15+int main(int argc, char *argv[]) {16+ int need=3;17+ if (argc<need+1) { // not enough words18+ printf("Please supply %d number(s).\n", need);19+ return 1;20+ }21+22+ { // excerpt for User's Guide starts here--------------------------|23+ decNumber one, mtwo, hundred; // constants24+ decNumber start, rate, years; // parameters25+ decNumber total; // result26+ decContext set; // working context27+ char string[DECNUMDIGITS+14]; // conversion buffer28+29+ decContextDefault(&set, DEC_INIT_BASE); // initialize30+ set.traps=0; // no traps31+ set.digits=25; // precision 2532+ decNumberFromString(&one, "1", &set); // set constants33+ decNumberFromString(&mtwo, "-2", &set);34+ decNumberFromString(&hundred, "100", &set);35+36+ decNumberFromString(&start, argv[1], &set); // parameter words37+ decNumberFromString(&rate, argv[2], &set);38+ decNumberFromString(&years, argv[3], &set);39+40+ decNumberDivide(&rate, &rate, &hundred, &set); // rate=rate/10041+ decNumberAdd(&rate, &rate, &one, &set); // rate=rate+142+ decNumberPower(&rate, &rate, &years, &set); // rate=rate^years43+ decNumberMultiply(&total, &rate, &start, &set); // total=rate*start44+ decNumberRescale(&total, &total, &mtwo, &set); // two digits please45+46+ decNumberToString(&total, string);47+ printf("%s at %s%% for %s years => %s\n",48+ argv[1], argv[2], argv[3], string);49+50+ } //---------------------------------------------------------------|51+ return 0;52+ } // mainadded:src/decNumber/example3.c+64 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example3.c -- calculate compound interest, passive checking9+// Arguments are investment, rate (%), and years10+11+#define DECNUMDIGITS 38 // work with up to 38 digits12+#include "decNumber.h" // base number library13+#include <stdio.h> // for printf14+15+int main(int argc, char *argv[]) {16+ int need=3;17+ if (argc<need+1) { // not enough words18+ printf("Please supply %d number(s).\n", need);19+ return 1;20+ }21+22+ { // start of Example 2 segment23+ decNumber one, mtwo, hundred; // constants24+ decNumber start, rate, years; // parameters25+ decNumber total; // result26+ decContext set; // working context27+ char string[DECNUMDIGITS+14]; // conversion buffer28+29+ decContextDefault(&set, DEC_INIT_BASE); // initialize30+ set.traps=0; // no traps31+ set.digits=25; // precision 2532+ decNumberFromString(&one, "1", &set); // set constants33+ decNumberFromString(&mtwo, "-2", &set);34+ decNumberFromString(&hundred, "100", &set);35+36+// [snip...37+ decNumberFromString(&start, argv[1], &set); // parameter words38+ decNumberFromString(&rate, argv[2], &set);39+ decNumberFromString(&years, argv[3], &set);40+ if (set.status & DEC_Errors) {41+ printf("An input argument word was invalid [%s]\n",42+ decContextStatusToString(&set));43+ return 1;44+ }45+ decNumberDivide(&rate, &rate, &hundred, &set); // rate=rate/10046+ decNumberAdd(&rate, &rate, &one, &set); // rate=rate+147+ decNumberPower(&rate, &rate, &years, &set); // rate=rate^years48+ decNumberMultiply(&total, &rate, &start, &set); // total=rate*start49+ decNumberRescale(&total, &total, &mtwo, &set); // two digits please50+ if (set.status & DEC_Errors) {51+ set.status &= DEC_Errors; // keep only errors52+ printf("Result could not be calculated [%s]\n",53+ decContextStatusToString(&set));54+ return 1;55+ }56+// ...snip]57+58+ decNumberToString(&total, string);59+ printf("%s at %s%% for %s years => %s\n",60+ argv[1], argv[2], argv[3], string);61+62+ } //---------------------------------------------------------------|63+ return 0;64+ } // mainadded:src/decNumber/example4.c+61 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example4.c -- add two numbers, active error handling9+// Arguments are two numbers10+11+#define DECNUMDIGITS 38 // work with up to 38 digits12+#include "decNumber.h" // base number library13+#include <stdio.h> // for printf14+15+// [snip...16+#include <signal.h> // signal handling17+#include <setjmp.h> // setjmp/longjmp18+19+jmp_buf preserve; // stack snapshot20+21+void signalHandler(int); // prototype for GCC22+void signalHandler(int sig) {23+ signal(SIGFPE, signalHandler); // re-enable24+ longjmp(preserve, sig); // branch to preserved point25+ }26+// ...snip]27+int main(int argc, char *argv[]) {28+ decNumber a, b; // working numbers29+ decContext set; // working context30+ char string[DECNUMDIGITS+14]; // conversion buffer31+ int value; // work variable32+33+ if (argc<3) { // not enough words34+ printf("Please supply two numbers to add.\n");35+ return 1;36+ }37+ decContextDefault(&set, DEC_INIT_BASE); // initialize38+39+// [snip...40+ signal(SIGFPE, signalHandler); // set up signal handler41+ value=setjmp(preserve); // preserve and test environment42+ if (value) { // (non-0 after longjmp)43+ set.status &= DEC_Errors; // keep only errors44+ printf("Signal trapped [%s].\n", decContextStatusToString(&set));45+ return 1;46+ }47+// ...snip]48+49+// [change from Example 1, here]50+ // leave traps enabled51+ set.digits=DECNUMDIGITS; // set precision52+53+ decNumberFromString(&a, argv[1], &set);54+ decNumberFromString(&b, argv[2], &set);55+56+ decNumberAdd(&a, &a, &b, &set); // A=A+B57+ decNumberToString(&a, string);58+59+ printf("%s + %s => %s\n", argv[1], argv[2], string);60+ return 0;61+ } // mainadded:src/decNumber/example5.c+36 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example5.c -- decimal64 conversions9+10+#include "decimal64.h" // decimal64 and decNumber library11+#include <stdio.h> // for (s)printf12+13+int main(int argc, char *argv[]) {14+ decimal64 a; // working decimal64 number15+ decNumber d; // working number16+ decContext set; // working context17+ char string[DECIMAL64_String]; // number->string buffer18+ char hexes[25]; // decimal64->hex buffer19+ int i; // counter20+21+ if (argc<2) { // not enough words22+ printf("Please supply a number.\n");23+ return 1;24+ }25+ decContextDefault(&set, DEC_INIT_DECIMAL64); // initialize26+27+ decimal64FromString(&a, argv[1], &set);28+ // lay out the decimal64 as eight hexadecimal pairs29+ for (i=0; i<8; i++) {30+ sprintf(&hexes[i*3], "%02x ", a.bytes[i]);31+ }32+ decimal64ToNumber(&a, &d);33+ decNumberToString(&d, string);34+ printf("%s => %s=> %s\n", argv[1], hexes, string);35+ return 0;36+ } // mainadded:src/decNumber/example6.c+61 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example6.c -- calculate compound interest, using Packed Decimal9+// Values are investment, rate (%), and years10+11+#include "decPacked.h" // base number library12+#include <stdio.h> // for printf13+14+int main(int argc, char *argv[]) {15+ { // excerpt for User's Guide starts here--------------------------|16+ decNumber one, mtwo, hundred; // constants17+ decNumber start, rate, years; // parameters18+ decNumber total; // result19+ decContext set; // working context20+21+ uint8_t startpack[]={0x01, 0x00, 0x00, 0x0C}; // investment=10000022+ int32_t startscale=0;23+ uint8_t ratepack[]={0x06, 0x5C}; // rate=6.5%24+ int32_t ratescale=1;25+ uint8_t yearspack[]={0x02, 0x0C}; // years=2026+ int32_t yearsscale=0;27+ uint8_t respack[16]; // result, packed28+ int32_t resscale; // ..29+ char hexes[49]; // for packed->hex30+ int i; // counter31+32+ if (argc<0) printf("%s", argv[1]); // noop for warning33+34+ decContextDefault(&set, DEC_INIT_BASE); // initialize35+ set.traps=0; // no traps36+ set.digits=25; // precision 2537+ decNumberFromString(&one, "1", &set); // set constants38+ decNumberFromString(&mtwo, "-2", &set);39+ decNumberFromString(&hundred, "100", &set);40+41+ decPackedToNumber(startpack, sizeof(startpack), &startscale, &start);42+ decPackedToNumber(ratepack, sizeof(ratepack), &ratescale, &rate);43+ decPackedToNumber(yearspack, sizeof(yearspack), &yearsscale, &years);44+45+ decNumberDivide(&rate, &rate, &hundred, &set); // rate=rate/10046+ decNumberAdd(&rate, &rate, &one, &set); // rate=rate+147+ decNumberPower(&rate, &rate, &years, &set); // rate=rate^years48+ decNumberMultiply(&total, &rate, &start, &set); // total=rate*start49+ decNumberRescale(&total, &total, &mtwo, &set); // two digits please50+51+ decPackedFromNumber(respack, sizeof(respack), &resscale, &total);52+53+ // lay out the total as sixteen hexadecimal pairs54+ for (i=0; i<16; i++) {55+ sprintf(&hexes[i*3], "%02x ", respack[i]);56+ }57+ printf("Result: %s (scale=%ld)\n", hexes, (long int)resscale);58+59+ } //---------------------------------------------------------------|60+ return 0;61+ } // mainadded:src/decNumber/example7.c+35 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001, 2008. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example7.c -- using decQuad to add two numbers together9+10+// compile: example7.c decContext.c decQuad.c11+12+#include "decQuad.h" // decQuad library13+#include <stdio.h> // for printf14+15+int main(int argc, char *argv[]) {16+ decQuad a, b; // working decQuads17+ decContext set; // working context18+ char string[DECQUAD_String]; // number->string buffer19+20+ decContextTestEndian(0); // warn if DECLITEND is wrong21+22+ if (argc<3) { // not enough words23+ printf("Please supply two numbers to add.\n");24+ return 1;25+ }26+ decContextDefault(&set, DEC_INIT_DECQUAD); // initialize27+28+ decQuadFromString(&a, argv[1], &set);29+ decQuadFromString(&b, argv[2], &set);30+ decQuadAdd(&a, &a, &b, &set); // a=a+b31+ decQuadToString(&a, string);32+33+ printf("%s + %s => %s\n", argv[1], argv[2], string);34+ return 0;35+ } // mainadded:src/decNumber/example8.c+39 added
1+/* ------------------------------------------------------------------ */2+/* Decimal Number Library Demonstration program */3+/* ------------------------------------------------------------------ */4+/* Copyright (c) IBM Corporation, 2001, 2007. All rights reserved. */5+/* ----------------------------------------------------------------+- */6+/* right margin -->| */7+8+// example8.c -- using decQuad with the decNumber module9+10+// compile: example8.c decContext.c decQuad.c11+// and: decNumber.c decimal128.c decimal64.c12+13+#include "decQuad.h" // decQuad library14+#include "decimal128.h" // interface to decNumber15+#include <stdio.h> // for printf16+17+int main(int argc, char *argv[]) {18+ decQuad a; // working decQuad19+ decNumber numa, numb; // working decNumbers20+ decContext set; // working context21+ char string[DECQUAD_String]; // number->string buffer22+23+ if (argc<3) { // not enough words24+ printf("Please supply two numbers for power(2*a, b).\n");25+ return 1;26+ }27+ decContextDefault(&set, DEC_INIT_DECQUAD); // initialize28+29+ decQuadFromString(&a, argv[1], &set); // get a30+ decQuadAdd(&a, &a, &a, &set); // double a31+ decQuadToNumber(&a, &numa); // convert to decNumber32+ decNumberFromString(&numb, argv[2], &set);33+ decNumberPower(&numa, &numa, &numb, &set); // numa=numa**numb34+ decQuadFromNumber(&a, &numa, &set); // back via a Quad35+ decQuadToString(&a, string); // ..36+37+ printf("power(2*%s, %s) => %s\n", argv[1], argv[2], string);38+ return 0;39+ } // mainadded:src/decNumber/ICU-license.html+45 added
1+<html>2+3+<head>4+<meta http-equiv="Content-Type" content="text/html; charset=us-ascii"></meta>5+<title>ICU License - ICU 1.8.1 and later</title>6+</head>7+8+<body>9+<h1>ICU License - ICU 1.8.1 and later</h1>10+<pre>11+COPYRIGHT AND PERMISSION NOTICE12+13+Copyright (c) 1995-2005 International Business Machines Corporation and others14+All rights reserved.15+16+Permission is hereby granted, free of charge, to any person obtaining a17+copy of this software and associated documentation files (the18+"Software"), to deal in the Software without restriction, including19+without limitation the rights to use, copy, modify, merge, publish,20+distribute, and/or sell copies of the Software, and to permit persons21+to whom the Software is furnished to do so, provided that the above22+copyright notice(s) and this permission notice appear in all copies of23+the Software and that both the above copyright notice(s) and this24+permission notice appear in supporting documentation.25+26+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS27+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF28+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT29+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR30+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL31+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING32+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,33+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION34+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.35+36+Except as contained in this notice, the name of a copyright holder37+shall not be used in advertising or otherwise to promote the sale, use38+or other dealings in this Software without prior written authorization39+of the copyright holder.40+41+--------------------------------------------------------------------------------42+All trademarks and registered trademarks mentioned herein are the property of their respective owners.43+</pre>44+</body>45+</html>added:src/decNumber/readme.txt+81 added
1+This is the readme.txt for the decNumber package. It includes2+instructions for compiling and testing the package; please read them.3+---------------------------------------------------------------------4+5+decNumber is distributed in two forms; as a complete package from6+the International Components for Unicode (ICU) site (under an as-is7+license), or as a collection of Open Source files from the GCC source8+repository (under the GPL license).9+10+If you are using the GCC files, you can obtain the documentation, the11+example files mentioned below, and this readme from the General12+Decimal Arithmetic web page -- http://speleotrove.com/decimal/ (the13+URL for the open source files is also linked from there).14+15+16+The ICU package17+---------------18+19+The ICU package includes the files:20+21+ * readme.txt (this file)22+23+ * ICU-license.html24+25+ * decNumber.pdf (documentation)26+27+ * The .c and .h file for each module in the package (see the28+ decNumber documentation), together with other included files.29+30+ * The .c files for each of the examples (example1.c through31+ example8.c).32+33+The ICU package is made available under the terms of the ICU License34+(ICU 1.8.1 and later) included in the package as ICU-license.html.35+Your use of that package indicates your acceptance of the terms and36+conditions of that Agreement.37+38+39+To use and check decNumber40+--------------------------41+42+ Please read the appropriate license and documentation before using43+ this package. If you are upgrading an existing use of decNumber44+ (with version <= 3.37) please read the Changes Appendix for later45+ versions -- you may need to change the DECLITEND flag.46+47+ 1. Compile and link example1.c, decNumber.c, and decContext.c48+ For instance, use:49+50+ gcc -o example1 example1.c decNumber.c decContext.c51+52+ Note: If your compiler does not provide stdint.h or if your C53+ compiler does not handle line comments (// ...), then see the54+ User's Guide section in the documentation for further information55+ (including a sample minimal stdint.h).56+57+ The use of compiler optimization is strongly recommended (e.g.,58+ -O3 for GCC or /O2 for Visual Studio).59+60+ 2. Run example1 with two numeric arguments, for example:61+62+ example1 1.23 1.2763+64+ this should display:65+66+ 1.23 + 1.27 => 2.5067+68+ 3. Similarly, try the other examples, at will.69+70+ Examples 2->4 require three files to be compiled, like Example 1.71+72+ Example 5 requires decimal64.c in addition to the core modules.73+74+ Example 6 requires decPacked.c in addition to the core modules.75+76+ Example 7 requires only example7.c decContext.c and decQuad.c77+78+ Example 8 requires example8.c, decContext.c, and decQuad.c, plus79+ decNumber.c, decimal128.c, and decimal64.c (the latter80+ for shared tables and code)81+modified:COPYING+38 added
66 unmodified lines67 WARRANTY. IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY68 REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY69 OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.70 71+72+73+jq uses parts of the open source C library "decNumber", which is distribured74+under the following license:75+76+77+ICU License - ICU 1.8.1 and later78+79+COPYRIGHT AND PERMISSION NOTICE80+81+Copyright (c) 1995-2005 International Business Machines Corporation and others82+All rights reserved.83+84+Permission is hereby granted, free of charge, to any person obtaining a85+copy of this software and associated documentation files (the86+"Software"), to deal in the Software without restriction, including87+without limitation the rights to use, copy, modify, merge, publish,88+distribute, and/or sell copies of the Software, and to permit persons89+to whom the Software is furnished to do so, provided that the above90+copyright notice(s) and this permission notice appear in all copies of91+the Software and that both the above copyright notice(s) and this92+permission notice appear in supporting documentation.93+94+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS95+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF96+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT97+OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR98+HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL99+INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING100+FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,101+NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION102+WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.103+104+Except as contained in this notice, the name of a copyright holder105+shall not be used in advertising or otherwise to promote the sale, use106+or other dealings in this Software without prior written authorization107+of the copyright holder.108+added:tests.out+101 added
1+Skipped 9 tests2+Testing '.[0]' at line number 373+Hit the number of tests limit (1), breaking4+1 of 1 tests passed (0 malformed)5+==9681== 17 bytes in 1 blocks are definitely lost in loss record 4 of 456+==9681== at 0x100180545: malloc (vg_replace_malloc.c:302)7+==9681== by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)8+==9681== by 0x10001F425: jv_number_with_literal (jv.c:193)9+==9681== by 0x10002F9C8: check_literal (jv_parse.c:508)10+==9681== by 0x10002EAA4: jv_parser_next (jv_parse.c:797)11+==9681== by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)12+==9681== by 0x10003544B: jq_yylex (lexer.l:90)13+==9681== by 0x100036FB4: yylex (parser.y:153)14+==9681== by 0x100037352: yyparse (parser.c:2292)15+==9681== by 0x10003B0FD: jq_parse (parser.y:967)16+==9681== by 0x100032CD4: load_program (linker.c:374)17+==9681== by 0x10001C5B3: jq_compile_args (execute.c:1172)18+==9681==19+20+21+Skipped 10 tests22+Testing '.[2]' at line number 4123+Hit the number of tests limit (1), breaking24+1 of 1 tests passed (0 malformed)25+==9690== 17 bytes in 1 blocks are definitely lost in loss record 4 of 4526+==9690== at 0x100180545: malloc (vg_replace_malloc.c:302)27+==9690== by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)28+==9690== by 0x10001F425: jv_number_with_literal (jv.c:193)29+==9690== by 0x10002F9C8: check_literal (jv_parse.c:508)30+==9690== by 0x10002EAA4: jv_parser_next (jv_parse.c:797)31+==9690== by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)32+==9690== by 0x10003544B: jq_yylex (lexer.l:90)33+==9690== by 0x100036FB4: yylex (parser.y:153)34+==9690== by 0x100037352: yyparse (parser.c:2292)35+==9690== by 0x10003B0FD: jq_parse (parser.y:967)36+==9690== by 0x100032CD4: load_program (linker.c:374)37+==9690== by 0x10001C5B3: jq_compile_args (execute.c:1172)38+==9690==39+40+Skipped 12 tests41+Testing '.[2:4]' at line number 4942+Hit the number of tests limit (1), breaking43+1 of 1 tests passed (0 malformed)44+==9713== 34 bytes in 2 blocks are definitely lost in loss record 15 of 4545+==9713== at 0x100180545: malloc (vg_replace_malloc.c:302)46+==9713== by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)47+==9713== by 0x10001F425: jv_number_with_literal (jv.c:193)48+==9713== by 0x10002F9C8: check_literal (jv_parse.c:508)49+==9713== by 0x10002EAA4: jv_parser_next (jv_parse.c:797)50+==9713== by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)51+==9713== by 0x10003544B: jq_yylex (lexer.l:90)52+==9713== by 0x100036FB4: yylex (parser.y:153)53+==9713== by 0x100037352: yyparse (parser.c:2292)54+==9713== by 0x10003B0FD: jq_parse (parser.y:967)55+==9713== by 0x100032CD4: load_program (linker.c:374)56+==9713== by 0x10001C5B3: jq_compile_args (execute.c:1172)57+==9713==58+59+Skipped 13 tests60+Testing '.[2:4]' at line number 5361+Hit the number of tests limit (1), breaking62+1 of 1 tests passed (0 malformed)63+==9714== 34 bytes in 2 blocks are definitely lost in loss record 15 of 4564+==9714== at 0x100180545: malloc (vg_replace_malloc.c:302)65+==9714== by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)66+==9714== by 0x10001F425: jv_number_with_literal (jv.c:193)67+==9714== by 0x10002F9C8: check_literal (jv_parse.c:508)68+==9714== by 0x10002EAA4: jv_parser_next (jv_parse.c:797)69+==9714== by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)70+==9714== by 0x10003544B: jq_yylex (lexer.l:90)71+==9714== by 0x100036FB4: yylex (parser.y:153)72+==9714== by 0x100037352: yyparse (parser.c:2292)73+==9714== by 0x10003B0FD: jq_parse (parser.y:967)74+==9714== by 0x100032CD4: load_program (linker.c:374)75+==9714== by 0x10001C5B3: jq_compile_args (execute.c:1172)76+==9714==77+78+Skipped 14 tests79+Testing '.[:3]' at line number 5780+Hit the number of tests limit (1), breaking81+1 of 1 tests passed (0 malformed)82+==9715== 17 bytes in 1 blocks are definitely lost in loss record 4 of 4583+==9715== at 0x100180545: malloc (vg_replace_malloc.c:302)84+==9715== by 0x1000240D8: jv_mem_alloc (jv_alloc.c:122)85+==9715== by 0x10001F425: jv_number_with_literal (jv.c:193)86+==9715== by 0x10002F9C8: check_literal (jv_parse.c:508)87+==9715== by 0x10002EAA4: jv_parser_next (jv_parse.c:797)88+==9715== by 0x10002FBF2: jv_parse_sized (jv_parse.c:830)89+==9715== by 0x10003544B: jq_yylex (lexer.l:90)90+==9715== by 0x100036FB4: yylex (parser.y:153)91+==9715== by 0x100037352: yyparse (parser.c:2292)92+==9715== by 0x10003B0FD: jq_parse (parser.y:967)93+==9715== by 0x100032CD4: load_program (linker.c:374)94+==9715== by 0x10001C5B3: jq_compile_args (execute.c:1172)95+==9715==96+97+Skipped 19 tests98+Testing '.foo, .bar' at line number 7899+Hit the number of tests limit (1), breaking100+1 of 1 tests passed (0 malformed)101+