decCommon.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  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. /* [email protected] */
  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., and
  30. // the functions are in strict alphabetical order.
  31. // Constants, tables, and debug function(s) are included only for QUAD
  32. // (which will always be compiled if DOUBLE or SINGLE are used).
  33. //
  34. // Whenever a decContext is used, only the status may be set (using
  35. // OR) or the rounding mode read; all other fields are ignored and
  36. // untouched.
  37. // names for simpler testing and default context
  38. #if DECPMAX==7
  39. #define SINGLE 1
  40. #define DOUBLE 0
  41. #define QUAD 0
  42. #define DEFCONTEXT DEC_INIT_DECIMAL32
  43. #elif DECPMAX==16
  44. #define SINGLE 0
  45. #define DOUBLE 1
  46. #define QUAD 0
  47. #define DEFCONTEXT DEC_INIT_DECIMAL64
  48. #elif DECPMAX==34
  49. #define SINGLE 0
  50. #define DOUBLE 0
  51. #define QUAD 1
  52. #define DEFCONTEXT DEC_INIT_DECIMAL128
  53. #else
  54. #error Unexpected DECPMAX value
  55. #endif
  56. /* Assertions */
  57. #if DECPMAX!=7 && DECPMAX!=16 && DECPMAX!=34
  58. #error Unexpected Pmax (DECPMAX) value for this module
  59. #endif
  60. // Assert facts about digit characters, etc.
  61. #if ('9'&0x0f)!=9
  62. #error This module assumes characters are of the form 0b....nnnn
  63. // where .... are don't care 4 bits and nnnn is 0000 through 1001
  64. #endif
  65. #if ('9'&0xf0)==('.'&0xf0)
  66. #error This module assumes '.' has a different mask than a digit
  67. #endif
  68. // Assert ToString lay-out conditions
  69. #if DECSTRING<DECPMAX+9
  70. #error ToString needs at least 8 characters for lead-in and dot
  71. #endif
  72. #if DECPMAX+DECEMAXD+5 > DECSTRING
  73. #error Exponent form can be too long for ToString to lay out safely
  74. #endif
  75. #if DECEMAXD > 4
  76. #error Exponent form is too long for ToString to lay out
  77. // Note: code for up to 9 digits exists in archives [decOct]
  78. #endif
  79. /* Private functions used here and possibly in decBasic.c, etc. */
  80. static decFloat * decFinalize(decFloat *, bcdnum *, decContext *);
  81. static Flag decBiStr(const char *, const char *, const char *);
  82. /* Macros and private tables; those which are not format-dependent */
  83. /* are only included if decQuad is being built. */
  84. /* ------------------------------------------------------------------ */
  85. /* Combination field lookup tables (uInts to save measurable work) */
  86. /* */
  87. /* DECCOMBEXP - 2 most-significant-bits of exponent (00, 01, or */
  88. /* 10), shifted left for format, or DECFLOAT_Inf/NaN */
  89. /* DECCOMBWEXP - The same, for the next-wider format (unless QUAD) */
  90. /* DECCOMBMSD - 4-bit most-significant-digit */
  91. /* [0 if the index is a special (Infinity or NaN)] */
  92. /* DECCOMBFROM - 5-bit combination field from EXP top bits and MSD */
  93. /* (placed in uInt so no shift is needed) */
  94. /* */
  95. /* DECCOMBEXP, DECCOMBWEXP, and DECCOMBMSD are indexed by the sign */
  96. /* and 5-bit combination field (0-63, the second half of the table */
  97. /* identical to the first half) */
  98. /* DECCOMBFROM is indexed by expTopTwoBits*16 + msd */
  99. /* */
  100. /* DECCOMBMSD and DECCOMBFROM are not format-dependent and so are */
  101. /* only included once, when QUAD is being built */
  102. /* ------------------------------------------------------------------ */
  103. static const uInt DECCOMBEXP[64]={
  104. 0, 0, 0, 0, 0, 0, 0, 0,
  105. 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,
  106. 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,
  107. 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,
  108. 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,
  109. 0, 0, 1<<DECECONL, 1<<DECECONL,
  110. 2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN,
  111. 0, 0, 0, 0, 0, 0, 0, 0,
  112. 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,
  113. 1<<DECECONL, 1<<DECECONL, 1<<DECECONL, 1<<DECECONL,
  114. 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,
  115. 2<<DECECONL, 2<<DECECONL, 2<<DECECONL, 2<<DECECONL,
  116. 0, 0, 1<<DECECONL, 1<<DECECONL,
  117. 2<<DECECONL, 2<<DECECONL, DECFLOAT_Inf, DECFLOAT_NaN};
  118. #if !QUAD
  119. static const uInt DECCOMBWEXP[64]={
  120. 0, 0, 0, 0, 0, 0, 0, 0,
  121. 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,
  122. 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,
  123. 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,
  124. 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,
  125. 0, 0, 1<<DECWECONL, 1<<DECWECONL,
  126. 2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN,
  127. 0, 0, 0, 0, 0, 0, 0, 0,
  128. 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,
  129. 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL, 1<<DECWECONL,
  130. 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,
  131. 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL, 2<<DECWECONL,
  132. 0, 0, 1<<DECWECONL, 1<<DECWECONL,
  133. 2<<DECWECONL, 2<<DECWECONL, DECFLOAT_Inf, DECFLOAT_NaN};
  134. #endif
  135. #if QUAD
  136. const uInt DECCOMBMSD[64]={
  137. 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
  138. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0,
  139. 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7,
  140. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 9, 8, 9, 0, 0};
  141. const uInt DECCOMBFROM[48]={
  142. 0x00000000, 0x04000000, 0x08000000, 0x0C000000, 0x10000000, 0x14000000,
  143. 0x18000000, 0x1C000000, 0x60000000, 0x64000000, 0x00000000, 0x00000000,
  144. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x20000000, 0x24000000,
  145. 0x28000000, 0x2C000000, 0x30000000, 0x34000000, 0x38000000, 0x3C000000,
  146. 0x68000000, 0x6C000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
  147. 0x00000000, 0x00000000, 0x40000000, 0x44000000, 0x48000000, 0x4C000000,
  148. 0x50000000, 0x54000000, 0x58000000, 0x5C000000, 0x70000000, 0x74000000,
  149. 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000};
  150. /* ------------------------------------------------------------------ */
  151. /* Request and include the tables to use for conversions */
  152. /* ------------------------------------------------------------------ */
  153. #define DEC_BCD2DPD 1 // 0-0x999 -> DPD
  154. #define DEC_BIN2DPD 1 // 0-999 -> DPD
  155. #define DEC_BIN2BCD8 1 // 0-999 -> ddd, len
  156. #define DEC_DPD2BCD8 1 // DPD -> ddd, len
  157. #define DEC_DPD2BIN 1 // DPD -> 0-999
  158. #define DEC_DPD2BINK 1 // DPD -> 0-999000
  159. #define DEC_DPD2BINM 1 // DPD -> 0-999000000
  160. #include "decDPD.h" // source of the lookup tables
  161. #endif
  162. /* ----------------------------------------------------------------- */
  163. /* decBiStr -- compare string with pairwise options */
  164. /* */
  165. /* targ is the string to compare */
  166. /* str1 is one of the strings to compare against (length may be 0) */
  167. /* str2 is the other; it must be the same length as str1 */
  168. /* */
  169. /* returns 1 if strings compare equal, (that is, targ is the same */
  170. /* length as str1 and str2, and each character of targ is in one */
  171. /* of str1 or str2 in the corresponding position), or 0 otherwise */
  172. /* */
  173. /* This is used for generic caseless compare, including the awkward */
  174. /* case of the Turkish dotted and dotless Is. Use as (for example): */
  175. /* if (decBiStr(test, "mike", "MIKE")) ... */
  176. /* ----------------------------------------------------------------- */
  177. static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
  178. for (;;targ++, str1++, str2++) {
  179. if (*targ!=*str1 && *targ!=*str2) return 0;
  180. // *targ has a match in one (or both, if terminator)
  181. if (*targ=='\0') break;
  182. } // forever
  183. return 1;
  184. } // decBiStr
  185. /* ------------------------------------------------------------------ */
  186. /* decFinalize -- adjust and store a final result */
  187. /* */
  188. /* df is the decFloat format number which gets the final result */
  189. /* num is the descriptor of the number to be checked and encoded */
  190. /* [its values, including the coefficient, may be modified] */
  191. /* set is the context to use */
  192. /* returns df */
  193. /* */
  194. /* The num descriptor may point to a bcd8 string of any length; this */
  195. /* string may have leading insignificant zeros. If it has more than */
  196. /* DECPMAX digits then the final digit can be a round-for-reround */
  197. /* digit (i.e., it may include a sticky bit residue). */
  198. /* */
  199. /* The exponent (q) may be one of the codes for a special value and */
  200. /* can be up to 999999999 for conversion from string. */
  201. /* */
  202. /* No error is possible, but Inexact, Underflow, and/or Overflow may */
  203. /* be set. */
  204. /* ------------------------------------------------------------------ */
  205. // Constant whose size varies with format; also the check for surprises
  206. static uByte allnines[DECPMAX]=
  207. #if SINGLE
  208. {9, 9, 9, 9, 9, 9, 9};
  209. #elif DOUBLE
  210. {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
  211. #elif QUAD
  212. {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  213. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
  214. #endif
  215. static decFloat * decFinalize(decFloat *df, bcdnum *num,
  216. decContext *set) {
  217. uByte *ub; // work
  218. uInt dpd; // ..
  219. uInt uiwork; // for macros
  220. uByte *umsd=num->msd; // local copy
  221. uByte *ulsd=num->lsd; // ..
  222. uInt encode; // encoding accumulator
  223. Int length; // coefficient length
  224. uByte buffer[ROUNDUP(DECPMAX+3, 4)]; // [+3 allows uInt padding]
  225. #if DECCHECK
  226. Int clen=ulsd-umsd+1;
  227. #if QUAD
  228. #define COEXTRA 2 // extra-long coefficent
  229. #else
  230. #define COEXTRA 0
  231. #endif
  232. if (clen<1 || clen>DECPMAX*3+2+COEXTRA)
  233. printf("decFinalize: suspect coefficient [length=%ld]\n", (LI)clen);
  234. if (num->sign!=0 && num->sign!=DECFLOAT_Sign)
  235. printf("decFinalize: bad sign [%08lx]\n", (LI)num->sign);
  236. if (!EXPISSPECIAL(num->exponent)
  237. && (num->exponent>1999999999 || num->exponent<-1999999999))
  238. printf("decFinalize: improbable exponent [%ld]\n", (LI)num->exponent);
  239. // decShowNum(num, "final");
  240. #endif
  241. // A special will have an 'exponent' which is very positive and a
  242. // coefficient < DECPMAX
  243. length=(uInt)(ulsd-umsd+1); // coefficient length
  244. if (!NUMISSPECIAL(num)) {
  245. Int drop; // digits to be dropped
  246. // skip leading insignificant zeros to calculate an exact length
  247. // [this is quite expensive]
  248. if (*umsd==0) {
  249. for (; umsd+3<ulsd && UBTOUI(umsd)==0;) umsd+=4;
  250. for (; *umsd==0 && umsd<ulsd;) umsd++;
  251. length=ulsd-umsd+1; // recalculate
  252. }
  253. drop=MAXI(length-DECPMAX, DECQTINY-num->exponent);
  254. // drop can now be > digits for bottom-clamp (subnormal) cases
  255. if (drop>0) { // rounding needed
  256. // (decFloatQuantize has very similar code to this, so any
  257. // changes may need to be made there, too)
  258. uByte *roundat; // -> re-round digit
  259. uByte reround; // reround value
  260. // printf("Rounding; drop=%ld\n", (LI)drop);
  261. num->exponent+=drop; // always update exponent
  262. // Three cases here:
  263. // 1. new LSD is in coefficient (almost always)
  264. // 2. new LSD is digit to left of coefficient (so MSD is
  265. // round-for-reround digit)
  266. // 3. new LSD is to left of case 2 (whole coefficient is sticky)
  267. // [duplicate check-stickies code to save a test]
  268. // [by-digit check for stickies as runs of zeros are rare]
  269. if (drop<length) { // NB lengths not addresses
  270. roundat=umsd+length-drop;
  271. reround=*roundat;
  272. for (ub=roundat+1; ub<=ulsd; ub++) {
  273. if (*ub!=0) { // non-zero to be discarded
  274. reround=DECSTICKYTAB[reround]; // apply sticky bit
  275. break; // [remainder don't-care]
  276. }
  277. } // check stickies
  278. ulsd=roundat-1; // new LSD
  279. }
  280. else { // edge case
  281. if (drop==length) {
  282. roundat=umsd;
  283. reround=*roundat;
  284. }
  285. else {
  286. roundat=umsd-1;
  287. reround=0;
  288. }
  289. for (ub=roundat+1; ub<=ulsd; ub++) {
  290. if (*ub!=0) { // non-zero to be discarded
  291. reround=DECSTICKYTAB[reround]; // apply sticky bit
  292. break; // [remainder don't-care]
  293. }
  294. } // check stickies
  295. *umsd=0; // coefficient is a 0
  296. ulsd=umsd; // ..
  297. }
  298. if (reround!=0) { // discarding non-zero
  299. uInt bump=0;
  300. set->status|=DEC_Inexact;
  301. // if adjusted exponent [exp+digits-1] is < EMIN then num is
  302. // subnormal -- so raise Underflow
  303. if (num->exponent<DECEMIN && (num->exponent+(ulsd-umsd+1)-1)<DECEMIN)
  304. set->status|=DEC_Underflow;
  305. // next decide whether increment of the coefficient is needed
  306. if (set->round==DEC_ROUND_HALF_EVEN) { // fastpath slowest case
  307. if (reround>5) bump=1; // >0.5 goes up
  308. else if (reround==5) // exactly 0.5000 ..
  309. bump=*ulsd & 0x01; // .. up iff [new] lsd is odd
  310. } // r-h-e
  311. else switch (set->round) {
  312. case DEC_ROUND_DOWN: {
  313. // no change
  314. break;} // r-d
  315. case DEC_ROUND_HALF_DOWN: {
  316. if (reround>5) bump=1;
  317. break;} // r-h-d
  318. case DEC_ROUND_HALF_UP: {
  319. if (reround>=5) bump=1;
  320. break;} // r-h-u
  321. case DEC_ROUND_UP: {
  322. if (reround>0) bump=1;
  323. break;} // r-u
  324. case DEC_ROUND_CEILING: {
  325. // same as _UP for positive numbers, and as _DOWN for negatives
  326. if (!num->sign && reround>0) bump=1;
  327. break;} // r-c
  328. case DEC_ROUND_FLOOR: {
  329. // same as _UP for negative numbers, and as _DOWN for positive
  330. // [negative reround cannot occur on 0]
  331. if (num->sign && reround>0) bump=1;
  332. break;} // r-f
  333. case DEC_ROUND_05UP: {
  334. if (reround>0) { // anything out there is 'sticky'
  335. // bump iff lsd=0 or 5; this cannot carry so it could be
  336. // effected immediately with no bump -- but the code
  337. // is clearer if this is done the same way as the others
  338. if (*ulsd==0 || *ulsd==5) bump=1;
  339. }
  340. break;} // r-r
  341. default: { // e.g., DEC_ROUND_MAX
  342. set->status|=DEC_Invalid_context;
  343. #if DECCHECK
  344. printf("Unknown rounding mode: %ld\n", (LI)set->round);
  345. #endif
  346. break;}
  347. } // switch (not r-h-e)
  348. // printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump);
  349. if (bump!=0) { // need increment
  350. // increment the coefficient; this might end up with 1000...
  351. // (after the all nines case)
  352. ub=ulsd;
  353. for(; ub-3>=umsd && UBTOUI(ub-3)==0x09090909; ub-=4) {
  354. UBFROMUI(ub-3, 0); // to 00000000
  355. }
  356. // [note ub could now be to left of msd, and it is not safe
  357. // to write to the the left of the msd]
  358. // now at most 3 digits left to non-9 (usually just the one)
  359. for (; ub>=umsd; *ub=0, ub--) {
  360. if (*ub==9) continue; // carry
  361. *ub+=1;
  362. break;
  363. }
  364. if (ub<umsd) { // had all-nines
  365. *umsd=1; // coefficient to 1000...
  366. // usually the 1000... coefficient can be used as-is
  367. if ((ulsd-umsd+1)==DECPMAX) {
  368. num->exponent++;
  369. }
  370. else {
  371. // if coefficient is shorter than Pmax then num is
  372. // subnormal, so extend it; this is safe as drop>0
  373. // (or, if the coefficient was supplied above, it could
  374. // not be 9); this may make the result normal.
  375. ulsd++;
  376. *ulsd=0;
  377. // [exponent unchanged]
  378. #if DECCHECK
  379. if (num->exponent!=DECQTINY) // sanity check
  380. printf("decFinalize: bad all-nines extend [^%ld, %ld]\n",
  381. (LI)num->exponent, (LI)(ulsd-umsd+1));
  382. #endif
  383. } // subnormal extend
  384. } // had all-nines
  385. } // bump needed
  386. } // inexact rounding
  387. length=ulsd-umsd+1; // recalculate (may be <DECPMAX)
  388. } // need round (drop>0)
  389. // The coefficient will now fit and has final length unless overflow
  390. // decShowNum(num, "rounded");
  391. // if exponent is >=emax may have to clamp, overflow, or fold-down
  392. if (num->exponent>DECEMAX-(DECPMAX-1)) { // is edge case
  393. // printf("overflow checks...\n");
  394. if (*ulsd==0 && ulsd==umsd) { // have zero
  395. num->exponent=DECEMAX-(DECPMAX-1); // clamp to max
  396. }
  397. else if ((num->exponent+length-1)>DECEMAX) { // > Nmax
  398. // Overflow -- these could go straight to encoding, here, but
  399. // instead num is adjusted to keep the code cleaner
  400. Flag needmax=0; // 1 for finite result
  401. set->status|=(DEC_Overflow | DEC_Inexact);
  402. switch (set->round) {
  403. case DEC_ROUND_DOWN: {
  404. needmax=1; // never Infinity
  405. break;} // r-d
  406. case DEC_ROUND_05UP: {
  407. needmax=1; // never Infinity
  408. break;} // r-05
  409. case DEC_ROUND_CEILING: {
  410. if (num->sign) needmax=1; // Infinity iff non-negative
  411. break;} // r-c
  412. case DEC_ROUND_FLOOR: {
  413. if (!num->sign) needmax=1; // Infinity iff negative
  414. break;} // r-f
  415. default: break; // Infinity in all other cases
  416. }
  417. if (!needmax) { // easy .. set Infinity
  418. num->exponent=DECFLOAT_Inf;
  419. *umsd=0; // be clean: coefficient to 0
  420. ulsd=umsd; // ..
  421. }
  422. else { // return Nmax
  423. umsd=allnines; // use constant array
  424. ulsd=allnines+DECPMAX-1;
  425. num->exponent=DECEMAX-(DECPMAX-1);
  426. }
  427. }
  428. else { // no overflow but non-zero and may have to fold-down
  429. Int shift=num->exponent-(DECEMAX-(DECPMAX-1));
  430. if (shift>0) { // fold-down needed
  431. // fold down needed; must copy to buffer in order to pad
  432. // with zeros safely; fortunately this is not the worst case
  433. // path because cannot have had a round
  434. uByte *s=umsd; // source
  435. uByte *t=buffer; // safe target
  436. uByte *tlsd=buffer+(ulsd-umsd)+shift; // target LSD
  437. // printf("folddown shift=%ld\n", (LI)shift);
  438. for (; s<=ulsd; s+=4, t+=4) UBFROMUI(t, UBTOUI(s));
  439. for (t=tlsd-shift+1; t<=tlsd; t+=4) UBFROMUI(t, 0); // pad 0s
  440. num->exponent-=shift;
  441. umsd=buffer;
  442. ulsd=tlsd;
  443. }
  444. } // fold-down?
  445. length=ulsd-umsd+1; // recalculate length
  446. } // high-end edge case
  447. } // finite number
  448. /*------------------------------------------------------------------*/
  449. /* At this point the result will properly fit the decFloat */
  450. /* encoding, and it can be encoded with no possibility of error */
  451. /*------------------------------------------------------------------*/
  452. // Following code does not alter coefficient (could be allnines array)
  453. // fast path possible when DECPMAX digits
  454. if (length==DECPMAX) {
  455. return decFloatFromBCD(df, num->exponent, umsd, num->sign);
  456. } // full-length
  457. // slower path when not a full-length number; must care about length
  458. // [coefficient length here will be < DECPMAX]
  459. if (!NUMISSPECIAL(num)) { // is still finite
  460. // encode the combination field and exponent continuation
  461. uInt uexp=(uInt)(num->exponent+DECBIAS); // biased exponent
  462. uInt code=(uexp>>DECECONL)<<4; // top two bits of exp
  463. // [msd==0]
  464. // look up the combination field and make high word
  465. encode=DECCOMBFROM[code]; // indexed by (0-2)*16+msd
  466. encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation
  467. }
  468. else encode=num->exponent; // special [already in word]
  469. encode|=num->sign; // add sign
  470. // private macro to extract a declet, n (where 0<=n<DECLETS and 0
  471. // refers to the declet from the least significant three digits)
  472. // and put the corresponding DPD code into dpd. Access to umsd and
  473. // ulsd (pointers to the most and least significant digit of the
  474. // variable-length coefficient) is assumed, along with use of a
  475. // working pointer, uInt *ub.
  476. // As not full-length then chances are there are many leading zeros
  477. // [and there may be a partial triad]
  478. #define getDPDt(dpd, n) ub=ulsd-(3*(n))-2; \
  479. if (ub<umsd-2) dpd=0; \
  480. else if (ub>=umsd) dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)]; \
  481. else {dpd=*(ub+2); if (ub+1==umsd) dpd+=*(ub+1)*16; dpd=BCD2DPD[dpd];}
  482. // place the declets in the encoding words and copy to result (df),
  483. // according to endianness; in all cases complete the sign word
  484. // first
  485. #if DECPMAX==7
  486. getDPDt(dpd, 1);
  487. encode|=dpd<<10;
  488. getDPDt(dpd, 0);
  489. encode|=dpd;
  490. DFWORD(df, 0)=encode; // just the one word
  491. #elif DECPMAX==16
  492. getDPDt(dpd, 4); encode|=dpd<<8;
  493. getDPDt(dpd, 3); encode|=dpd>>2;
  494. DFWORD(df, 0)=encode;
  495. encode=dpd<<30;
  496. getDPDt(dpd, 2); encode|=dpd<<20;
  497. getDPDt(dpd, 1); encode|=dpd<<10;
  498. getDPDt(dpd, 0); encode|=dpd;
  499. DFWORD(df, 1)=encode;
  500. #elif DECPMAX==34
  501. getDPDt(dpd,10); encode|=dpd<<4;
  502. getDPDt(dpd, 9); encode|=dpd>>6;
  503. DFWORD(df, 0)=encode;
  504. encode=dpd<<26;
  505. getDPDt(dpd, 8); encode|=dpd<<16;
  506. getDPDt(dpd, 7); encode|=dpd<<6;
  507. getDPDt(dpd, 6); encode|=dpd>>4;
  508. DFWORD(df, 1)=encode;
  509. encode=dpd<<28;
  510. getDPDt(dpd, 5); encode|=dpd<<18;
  511. getDPDt(dpd, 4); encode|=dpd<<8;
  512. getDPDt(dpd, 3); encode|=dpd>>2;
  513. DFWORD(df, 2)=encode;
  514. encode=dpd<<30;
  515. getDPDt(dpd, 2); encode|=dpd<<20;
  516. getDPDt(dpd, 1); encode|=dpd<<10;
  517. getDPDt(dpd, 0); encode|=dpd;
  518. DFWORD(df, 3)=encode;
  519. #endif
  520. // printf("Status: %08lx\n", (LI)set->status);
  521. // decFloatShow(df, "final2");
  522. return df;
  523. } // decFinalize
  524. /* ------------------------------------------------------------------ */
  525. /* decFloatFromBCD -- set decFloat from exponent, BCD8, and sign */
  526. /* */
  527. /* df is the target decFloat */
  528. /* exp is the in-range unbiased exponent, q, or a special value in */
  529. /* the form returned by decFloatGetExponent */
  530. /* bcdar holds DECPMAX digits to set the coefficient from, one */
  531. /* digit in each byte (BCD8 encoding); the first (MSD) is ignored */
  532. /* if df is a NaN; all are ignored if df is infinite. */
  533. /* All bytes must be in 0-9; results are undefined otherwise. */
  534. /* sig is DECFLOAT_Sign to set the sign bit, 0 otherwise */
  535. /* returns df, which will be canonical */
  536. /* */
  537. /* No error is possible, and no status will be set. */
  538. /* ------------------------------------------------------------------ */
  539. decFloat * decFloatFromBCD(decFloat *df, Int exp, const uByte *bcdar,
  540. Int sig) {
  541. uInt encode, dpd; // work
  542. const uByte *ub; // ..
  543. if (EXPISSPECIAL(exp)) encode=exp|sig;// specials already encoded
  544. else { // is finite
  545. // encode the combination field and exponent continuation
  546. uInt uexp=(uInt)(exp+DECBIAS); // biased exponent
  547. uInt code=(uexp>>DECECONL)<<4; // top two bits of exp
  548. code+=bcdar[0]; // add msd
  549. // look up the combination field and make high word
  550. encode=DECCOMBFROM[code]|sig; // indexed by (0-2)*16+msd
  551. encode|=(uexp<<(32-6-DECECONL)) & 0x03ffffff; // exponent continuation
  552. }
  553. // private macro to extract a declet, n (where 0<=n<DECLETS and 0
  554. // refers to the declet from the least significant three digits)
  555. // and put the corresponding DPD code into dpd.
  556. // Use of a working pointer, uInt *ub, is assumed.
  557. #define getDPDb(dpd, n) ub=bcdar+DECPMAX-1-(3*(n))-2; \
  558. dpd=BCD2DPD[(*ub*256)+(*(ub+1)*16)+*(ub+2)];
  559. // place the declets in the encoding words and copy to result (df),
  560. // according to endianness; in all cases complete the sign word
  561. // first
  562. #if DECPMAX==7
  563. getDPDb(dpd, 1);
  564. encode|=dpd<<10;
  565. getDPDb(dpd, 0);
  566. encode|=dpd;
  567. DFWORD(df, 0)=encode; // just the one word
  568. #elif DECPMAX==16
  569. getDPDb(dpd, 4); encode|=dpd<<8;
  570. getDPDb(dpd, 3); encode|=dpd>>2;
  571. DFWORD(df, 0)=encode;
  572. encode=dpd<<30;
  573. getDPDb(dpd, 2); encode|=dpd<<20;
  574. getDPDb(dpd, 1); encode|=dpd<<10;
  575. getDPDb(dpd, 0); encode|=dpd;
  576. DFWORD(df, 1)=encode;
  577. #elif DECPMAX==34
  578. getDPDb(dpd,10); encode|=dpd<<4;
  579. getDPDb(dpd, 9); encode|=dpd>>6;
  580. DFWORD(df, 0)=encode;
  581. encode=dpd<<26;
  582. getDPDb(dpd, 8); encode|=dpd<<16;
  583. getDPDb(dpd, 7); encode|=dpd<<6;
  584. getDPDb(dpd, 6); encode|=dpd>>4;
  585. DFWORD(df, 1)=encode;
  586. encode=dpd<<28;
  587. getDPDb(dpd, 5); encode|=dpd<<18;
  588. getDPDb(dpd, 4); encode|=dpd<<8;
  589. getDPDb(dpd, 3); encode|=dpd>>2;
  590. DFWORD(df, 2)=encode;
  591. encode=dpd<<30;
  592. getDPDb(dpd, 2); encode|=dpd<<20;
  593. getDPDb(dpd, 1); encode|=dpd<<10;
  594. getDPDb(dpd, 0); encode|=dpd;
  595. DFWORD(df, 3)=encode;
  596. #endif
  597. // decFloatShow(df, "fromB");
  598. return df;
  599. } // decFloatFromBCD
  600. /* ------------------------------------------------------------------ */
  601. /* decFloatFromPacked -- set decFloat from exponent and packed BCD */
  602. /* */
  603. /* df is the target decFloat */
  604. /* exp is the in-range unbiased exponent, q, or a special value in */
  605. /* the form returned by decFloatGetExponent */
  606. /* packed holds DECPMAX packed decimal digits plus a sign nibble */
  607. /* (all 6 codes are OK); the first (MSD) is ignored if df is a NaN */
  608. /* and all except sign are ignored if df is infinite. For DOUBLE */
  609. /* and QUAD the first (pad) nibble is also ignored in all cases. */
  610. /* All coefficient nibbles must be in 0-9 and sign in A-F; results */
  611. /* are undefined otherwise. */
  612. /* returns df, which will be canonical */
  613. /* */
  614. /* No error is possible, and no status will be set. */
  615. /* ------------------------------------------------------------------ */
  616. decFloat * decFloatFromPacked(decFloat *df, Int exp, const uByte *packed) {
  617. uByte bcdar[DECPMAX+2]; // work [+1 for pad, +1 for sign]
  618. const uByte *ip; // ..
  619. uByte *op; // ..
  620. Int sig=0; // sign
  621. // expand coefficient and sign to BCDAR
  622. #if SINGLE
  623. op=bcdar+1; // no pad digit
  624. #else
  625. op=bcdar; // first (pad) digit ignored
  626. #endif
  627. for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {
  628. *op++=*ip>>4;
  629. *op++=(uByte)(*ip&0x0f); // [final nibble is sign]
  630. }
  631. op--; // -> sign byte
  632. if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;
  633. if (EXPISSPECIAL(exp)) { // Infinity or NaN
  634. if (!EXPISINF(exp)) bcdar[1]=0; // a NaN: ignore MSD
  635. else memset(bcdar+1, 0, DECPMAX); // Infinite: coefficient to 0
  636. }
  637. return decFloatFromBCD(df, exp, bcdar+1, sig);
  638. } // decFloatFromPacked
  639. /* ------------------------------------------------------------------ */
  640. /* decFloatFromPackedChecked -- set from exponent and packed; checked */
  641. /* */
  642. /* df is the target decFloat */
  643. /* exp is the in-range unbiased exponent, q, or a special value in */
  644. /* the form returned by decFloatGetExponent */
  645. /* packed holds DECPMAX packed decimal digits plus a sign nibble */
  646. /* (all 6 codes are OK); the first (MSD) must be 0 if df is a NaN */
  647. /* and all digits must be 0 if df is infinite. For DOUBLE and */
  648. /* QUAD the first (pad) nibble must be 0. */
  649. /* All coefficient nibbles must be in 0-9 and sign in A-F. */
  650. /* returns df, which will be canonical or NULL if any of the */
  651. /* requirements are not met (if this case df is unchanged); that */
  652. /* is, the input data must be as returned by decFloatToPacked, */
  653. /* except that all six sign codes are acccepted. */
  654. /* */
  655. /* No status will be set. */
  656. /* ------------------------------------------------------------------ */
  657. decFloat * decFloatFromPackedChecked(decFloat *df, Int exp,
  658. const uByte *packed) {
  659. uByte bcdar[DECPMAX+2]; // work [+1 for pad, +1 for sign]
  660. const uByte *ip; // ..
  661. uByte *op; // ..
  662. Int sig=0; // sign
  663. // expand coefficient and sign to BCDAR
  664. #if SINGLE
  665. op=bcdar+1; // no pad digit
  666. #else
  667. op=bcdar; // first (pad) digit here
  668. #endif
  669. for (ip=packed; ip<packed+((DECPMAX+2)/2); ip++) {
  670. *op=*ip>>4;
  671. if (*op>9) return NULL;
  672. op++;
  673. *op=(uByte)(*ip&0x0f); // [final nibble is sign]
  674. if (*op>9 && ip<packed+((DECPMAX+2)/2)-1) return NULL;
  675. op++;
  676. }
  677. op--; // -> sign byte
  678. if (*op<=9) return NULL; // bad sign
  679. if (*op==DECPMINUS || *op==DECPMINUSALT) sig=DECFLOAT_Sign;
  680. #if !SINGLE
  681. if (bcdar[0]!=0) return NULL; // bad pad nibble
  682. #endif
  683. if (EXPISNAN(exp)) { // a NaN
  684. if (bcdar[1]!=0) return NULL; // bad msd
  685. } // NaN
  686. else if (EXPISINF(exp)) { // is infinite
  687. Int i;
  688. for (i=0; i<DECPMAX; i++) {
  689. if (bcdar[i+1]!=0) return NULL; // should be all zeros
  690. }
  691. } // infinity
  692. else { // finite
  693. // check the exponent is in range
  694. if (exp>DECEMAX-DECPMAX+1) return NULL;
  695. if (exp<DECEMIN-DECPMAX+1) return NULL;
  696. }
  697. return decFloatFromBCD(df, exp, bcdar+1, sig);
  698. } // decFloatFromPacked
  699. /* ------------------------------------------------------------------ */
  700. /* decFloatFromString -- conversion from numeric string */
  701. /* */
  702. /* result is the decFloat format number which gets the result of */
  703. /* the conversion */
  704. /* *string is the character string which should contain a valid */
  705. /* number (which may be a special value), \0-terminated */
  706. /* If there are too many significant digits in the */
  707. /* coefficient it will be rounded. */
  708. /* set is the context */
  709. /* returns result */
  710. /* */
  711. /* The length of the coefficient and the size of the exponent are */
  712. /* checked by this routine, so the correct error (Underflow or */
  713. /* Overflow) can be reported or rounding applied, as necessary. */
  714. /* */
  715. /* There is no limit to the coefficient length for finite inputs; */
  716. /* NaN payloads must be integers with no more than DECPMAX-1 digits. */
  717. /* Exponents may have up to nine significant digits. */
  718. /* */
  719. /* If bad syntax is detected, the result will be a quiet NaN. */
  720. /* ------------------------------------------------------------------ */
  721. decFloat * decFloatFromString(decFloat *result, const char *string,
  722. decContext *set) {
  723. Int digits; // count of digits in coefficient
  724. const char *dotchar=NULL; // where dot was found [NULL if none]
  725. const char *cfirst=string; // -> first character of decimal part
  726. const char *c; // work
  727. uByte *ub; // ..
  728. uInt uiwork; // for macros
  729. bcdnum num; // collects data for finishing
  730. uInt error=DEC_Conversion_syntax; // assume the worst
  731. uByte buffer[ROUNDUP(DECSTRING+11, 8)]; // room for most coefficents,
  732. // some common rounding, +3, & pad
  733. #if DECTRACE
  734. // printf("FromString %s ...\n", string);
  735. #endif
  736. for(;;) { // once-only 'loop'
  737. num.sign=0; // assume non-negative
  738. num.msd=buffer; // MSD is here always
  739. // detect and validate the coefficient, including any leading,
  740. // trailing, or embedded '.'
  741. // [could test four-at-a-time here (saving 10% for decQuads),
  742. // but that risks storage violation because the position of the
  743. // terminator is unknown]
  744. for (c=string;; c++) { // -> input character
  745. if (((unsigned)(*c-'0'))<=9) continue; // '0' through '9' is good
  746. if (*c=='\0') break; // most common non-digit
  747. if (*c=='.') {
  748. if (dotchar!=NULL) break; // not first '.'
  749. dotchar=c; // record offset into decimal part
  750. continue;}
  751. if (c==string) { // first in string...
  752. if (*c=='-') { // valid - sign
  753. cfirst++;
  754. num.sign=DECFLOAT_Sign;
  755. continue;}
  756. if (*c=='+') { // valid + sign
  757. cfirst++;
  758. continue;}
  759. }
  760. // *c is not a digit, terminator, or a valid +, -, or '.'
  761. break;
  762. } // c loop
  763. digits=(uInt)(c-cfirst); // digits (+1 if a dot)
  764. if (digits>0) { // had digits and/or dot
  765. const char *clast=c-1; // note last coefficient char position
  766. Int exp=0; // exponent accumulator
  767. if (*c!='\0') { // something follows the coefficient
  768. uInt edig; // unsigned work
  769. // had some digits and more to come; expect E[+|-]nnn now
  770. const char *firstexp; // exponent first non-zero
  771. if (*c!='E' && *c!='e') break;
  772. c++; // to (optional) sign
  773. if (*c=='-' || *c=='+') c++; // step over sign (c=clast+2)
  774. if (*c=='\0') break; // no digits! (e.g., '1.2E')
  775. for (; *c=='0';) c++; // skip leading zeros [even last]
  776. firstexp=c; // remember start [maybe '\0']
  777. // gather exponent digits
  778. edig=(uInt)*c-(uInt)'0';
  779. if (edig<=9) { // [check not bad or terminator]
  780. exp+=edig; // avoid initial X10
  781. c++;
  782. for (;; c++) {
  783. edig=(uInt)*c-(uInt)'0';
  784. if (edig>9) break;
  785. exp=exp*10+edig;
  786. }
  787. }
  788. // if not now on the '\0', *c must not be a digit
  789. if (*c!='\0') break;
  790. // (this next test must be after the syntax checks)
  791. // if definitely more than the possible digits for format then
  792. // the exponent may have wrapped, so simply set it to a certain
  793. // over/underflow value
  794. if (c>firstexp+DECEMAXD) exp=DECEMAX*2;
  795. if (*(clast+2)=='-') exp=-exp; // was negative
  796. } // exponent part
  797. if (dotchar!=NULL) { // had a '.'
  798. digits--; // remove from digits count
  799. if (digits==0) break; // was dot alone: bad syntax
  800. exp-=(Int)(clast-dotchar); // adjust exponent
  801. // [the '.' can now be ignored]
  802. }
  803. num.exponent=exp; // exponent is good; store it
  804. // Here when whole string has been inspected and syntax is good
  805. // cfirst->first digit or dot, clast->last digit or dot
  806. error=0; // no error possible now
  807. // if the number of digits in the coefficient will fit in buffer
  808. // then it can simply be converted to bcd8 and copied -- decFinalize
  809. // will take care of leading zeros and rounding; the buffer is big
  810. // enough for all canonical coefficients, including 0.00000nn...
  811. ub=buffer;
  812. if (digits<=(Int)(sizeof(buffer)-3)) { // [-3 allows by-4s copy]
  813. c=cfirst;
  814. if (dotchar!=NULL) { // a dot to worry about
  815. if (*(c+1)=='.') { // common canonical case
  816. *ub++=(uByte)(*c-'0'); // copy leading digit
  817. c+=2; // prepare to handle rest
  818. }
  819. else for (; c<=clast;) { // '.' could be anywhere
  820. // as usual, go by fours when safe; NB it has been asserted
  821. // that a '.' does not have the same mask as a digit
  822. if (c<=clast-3 // safe for four
  823. && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // test four
  824. UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f); // to BCD8
  825. ub+=4;
  826. c+=4;
  827. continue;
  828. }
  829. if (*c=='.') { // found the dot
  830. c++; // step over it ..
  831. break; // .. and handle the rest
  832. }
  833. *ub++=(uByte)(*c++-'0');
  834. }
  835. } // had dot
  836. // Now no dot; do this by fours (where safe)
  837. for (; c<=clast-3; c+=4, ub+=4) UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f);
  838. for (; c<=clast; c++, ub++) *ub=(uByte)(*c-'0');
  839. num.lsd=buffer+digits-1; // record new LSD
  840. } // fits
  841. else { // too long for buffer
  842. // [This is a rare and unusual case; arbitrary-length input]
  843. // strip leading zeros [but leave final 0 if all 0's]
  844. {
  845. const char* cfirst2=NULL;
  846. for (; cfirst<=clast; cfirst++) {
  847. if (*cfirst == '.') continue; // [ignore]
  848. cfirst2=cfirst; // let's save the position of this digit
  849. if (*cfirst!='0') break; // done
  850. digits--; // 0 stripped
  851. } // cfirst
  852. if(clast<cfirst) { // all the symbols are ZEROs
  853. digits=1;
  854. }
  855. cfirst=cfirst2;
  856. } // local - at least one leading 0
  857. // the coefficient is now as short as possible, but may still
  858. // be too long; copy up to Pmax+1 digits to the buffer, then
  859. // just record any non-zeros (set round-for-reround digit)
  860. for (c=cfirst; c<=clast && ub<=buffer+DECPMAX; c++) {
  861. // (see commentary just above)
  862. if (c<=clast-3 // safe for four
  863. && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // four digits
  864. UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f); // to BCD8
  865. ub+=4;
  866. c+=3; // [will become 4]
  867. continue;
  868. }
  869. if (*c=='.') continue; // [ignore]
  870. *ub++=(uByte)(*c-'0');
  871. }
  872. ub--; // -> LSD
  873. for (; c<=clast; c++) { // inspect remaining chars
  874. if (*c!='0') { // sticky bit needed
  875. if (*c=='.') continue; // [ignore]
  876. *ub=DECSTICKYTAB[*ub]; // update round-for-reround
  877. break; // no need to look at more
  878. }
  879. }
  880. num.lsd=ub; // record LSD
  881. // adjust exponent for dropped digits
  882. num.exponent+=digits-(Int)(ub-buffer+1);
  883. } // too long for buffer
  884. } // digits and/or dot
  885. else { // no digits or dot were found
  886. // only Infinities and NaNs are allowed, here
  887. if (*c=='\0') break; // nothing there is bad
  888. buffer[0]=0; // default a coefficient of 0
  889. num.lsd=buffer; // ..
  890. if (decBiStr(c, "infinity", "INFINITY")
  891. || decBiStr(c, "inf", "INF")) num.exponent=DECFLOAT_Inf;
  892. else { // should be a NaN
  893. num.exponent=DECFLOAT_qNaN; // assume quiet NaN
  894. if (*c=='s' || *c=='S') { // probably an sNaN
  895. num.exponent=DECFLOAT_sNaN; // effect the 's'
  896. c++; // and step over it
  897. }
  898. if (*c!='N' && *c!='n') break; // check caseless "NaN"
  899. c++;
  900. if (*c!='a' && *c!='A') break; // ..
  901. c++;
  902. if (*c!='N' && *c!='n') break; // ..
  903. c++;
  904. // now either nothing, or nnnn payload (no dots), expected
  905. // -> start of integer, and skip leading 0s [including plain 0]
  906. for (cfirst=c; *cfirst=='0';) cfirst++;
  907. if (*cfirst!='\0') { // not empty or all-0, payload
  908. // payload found; check all valid digits and copy to buffer as bcd8
  909. ub=buffer;
  910. for (c=cfirst;; c++, ub++) {
  911. if ((unsigned)(*c-'0')>9) break; // quit if not 0-9
  912. if (c-cfirst==DECPMAX-1) break; // too many digits
  913. *ub=(uByte)(*c-'0'); // good bcd8
  914. }
  915. if (*c!='\0') break; // not all digits, or too many
  916. num.lsd=ub-1; // record new LSD
  917. }
  918. } // NaN or sNaN
  919. error=0; // syntax is OK
  920. } // digits=0 (special expected)
  921. break; // drop out
  922. } // [for(;;) once-loop]
  923. // decShowNum(&num, "fromStr");
  924. if (error!=0) {
  925. set->status|=error;
  926. num.exponent=DECFLOAT_qNaN; // set up quiet NaN
  927. num.sign=0; // .. with 0 sign
  928. buffer[0]=0; // .. and coefficient
  929. num.lsd=buffer; // ..
  930. // decShowNum(&num, "oops");
  931. }
  932. // decShowNum(&num, "dffs");
  933. decFinalize(result, &num, set); // round, check, and lay out
  934. // decFloatShow(result, "fromString");
  935. return result;
  936. } // decFloatFromString
  937. /* ------------------------------------------------------------------ */
  938. /* decFloatFromWider -- conversion from next-wider format */
  939. /* */
  940. /* result is the decFloat format number which gets the result of */
  941. /* the conversion */
  942. /* wider is the decFloatWider format number which will be narrowed */
  943. /* set is the context */
  944. /* returns result */
  945. /* */
  946. /* Narrowing can cause rounding, overflow, etc., but not Invalid */
  947. /* operation (sNaNs are copied and do not signal). */
  948. /* ------------------------------------------------------------------ */
  949. // narrow-to is not possible for decQuad format numbers; simply omit
  950. #if !QUAD
  951. decFloat * decFloatFromWider(decFloat *result, const decFloatWider *wider,
  952. decContext *set) {
  953. bcdnum num; // collects data for finishing
  954. uByte bcdar[DECWPMAX]; // room for wider coefficient
  955. uInt widerhi=DFWWORD(wider, 0); // top word
  956. Int exp;
  957. GETWCOEFF(wider, bcdar);
  958. num.msd=bcdar; // MSD is here always
  959. num.lsd=bcdar+DECWPMAX-1; // LSD is here always
  960. num.sign=widerhi&0x80000000; // extract sign [DECFLOAT_Sign=Neg]
  961. // decode the wider combination field to exponent
  962. exp=DECCOMBWEXP[widerhi>>26]; // decode from wider combination field
  963. // if it is a special there's nothing to do unless sNaN; if it's
  964. // finite then add the (wider) exponent continuation and unbias
  965. if (EXPISSPECIAL(exp)) exp=widerhi&0x7e000000; // include sNaN selector
  966. else exp+=GETWECON(wider)-DECWBIAS;
  967. num.exponent=exp;
  968. // decShowNum(&num, "dffw");
  969. return decFinalize(result, &num, set);// round, check, and lay out
  970. } // decFloatFromWider
  971. #endif
  972. /* ------------------------------------------------------------------ */
  973. /* decFloatGetCoefficient -- get coefficient as BCD8 */
  974. /* */
  975. /* df is the decFloat from which to extract the coefficient */
  976. /* bcdar is where DECPMAX bytes will be written, one BCD digit in */
  977. /* each byte (BCD8 encoding); if df is a NaN the first byte will */
  978. /* be zero, and if it is infinite they will all be zero */
  979. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  980. /* 0 otherwise) */
  981. /* */
  982. /* No error is possible, and no status will be set. If df is a */
  983. /* special value the array is set to zeros (for Infinity) or to the */
  984. /* payload of a qNaN or sNaN. */
  985. /* ------------------------------------------------------------------ */
  986. Int decFloatGetCoefficient(const decFloat *df, uByte *bcdar) {
  987. if (DFISINF(df)) memset(bcdar, 0, DECPMAX);
  988. else {
  989. GETCOEFF(df, bcdar); // use macro
  990. if (DFISNAN(df)) bcdar[0]=0; // MSD needs correcting
  991. }
  992. return GETSIGN(df);
  993. } // decFloatGetCoefficient
  994. /* ------------------------------------------------------------------ */
  995. /* decFloatGetExponent -- get unbiased exponent */
  996. /* */
  997. /* df is the decFloat from which to extract the exponent */
  998. /* returns the exponent, q. */
  999. /* */
  1000. /* No error is possible, and no status will be set. If df is a */
  1001. /* special value the first seven bits of the decFloat are returned, */
  1002. /* left adjusted and with the first (sign) bit set to 0 (followed by */
  1003. /* 25 0 bits). e.g., -sNaN would return 0x7e000000 (DECFLOAT_sNaN). */
  1004. /* ------------------------------------------------------------------ */
  1005. Int decFloatGetExponent(const decFloat *df) {
  1006. if (DFISSPECIAL(df)) return DFWORD(df, 0)&0x7e000000;
  1007. return GETEXPUN(df);
  1008. } // decFloatGetExponent
  1009. /* ------------------------------------------------------------------ */
  1010. /* decFloatSetCoefficient -- set coefficient from BCD8 */
  1011. /* */
  1012. /* df is the target decFloat (and source of exponent/special value) */
  1013. /* bcdar holds DECPMAX digits to set the coefficient from, one */
  1014. /* digit in each byte (BCD8 encoding); the first (MSD) is ignored */
  1015. /* if df is a NaN; all are ignored if df is infinite. */
  1016. /* sig is DECFLOAT_Sign to set the sign bit, 0 otherwise */
  1017. /* returns df, which will be canonical */
  1018. /* */
  1019. /* No error is possible, and no status will be set. */
  1020. /* ------------------------------------------------------------------ */
  1021. decFloat * decFloatSetCoefficient(decFloat *df, const uByte *bcdar,
  1022. Int sig) {
  1023. uInt exp; // for exponent
  1024. uByte bcdzero[DECPMAX]; // for infinities
  1025. // Exponent/special code is extracted from df
  1026. if (DFISSPECIAL(df)) {
  1027. exp=DFWORD(df, 0)&0x7e000000;
  1028. if (DFISINF(df)) {
  1029. memset(bcdzero, 0, DECPMAX);
  1030. return decFloatFromBCD(df, exp, bcdzero, sig);
  1031. }
  1032. }
  1033. else exp=GETEXPUN(df);
  1034. return decFloatFromBCD(df, exp, bcdar, sig);
  1035. } // decFloatSetCoefficient
  1036. /* ------------------------------------------------------------------ */
  1037. /* decFloatSetExponent -- set exponent or special value */
  1038. /* */
  1039. /* df is the target decFloat (and source of coefficient/payload) */
  1040. /* set is the context for reporting status */
  1041. /* exp is the unbiased exponent, q, or a special value in the form */
  1042. /* returned by decFloatGetExponent */
  1043. /* returns df, which will be canonical */
  1044. /* */
  1045. /* No error is possible, but Overflow or Underflow might occur. */
  1046. /* ------------------------------------------------------------------ */
  1047. decFloat * decFloatSetExponent(decFloat *df, decContext *set, Int exp) {
  1048. uByte bcdcopy[DECPMAX]; // for coefficient
  1049. bcdnum num; // work
  1050. num.exponent=exp;
  1051. num.sign=decFloatGetCoefficient(df, bcdcopy); // extract coefficient
  1052. if (DFISSPECIAL(df)) { // MSD or more needs correcting
  1053. if (DFISINF(df)) memset(bcdcopy, 0, DECPMAX);
  1054. bcdcopy[0]=0;
  1055. }
  1056. num.msd=bcdcopy;
  1057. num.lsd=bcdcopy+DECPMAX-1;
  1058. return decFinalize(df, &num, set);
  1059. } // decFloatSetExponent
  1060. /* ------------------------------------------------------------------ */
  1061. /* decFloatRadix -- returns the base (10) */
  1062. /* */
  1063. /* df is any decFloat of this format */
  1064. /* ------------------------------------------------------------------ */
  1065. uInt decFloatRadix(const decFloat *df) {
  1066. if (df) return 10; // to placate compiler
  1067. return 10;
  1068. } // decFloatRadix
  1069. /* The following function is not available if DECPRINT=0 */
  1070. #if DECPRINT
  1071. /* ------------------------------------------------------------------ */
  1072. /* decFloatShow -- printf a decFloat in hexadecimal and decimal */
  1073. /* df is the decFloat to show */
  1074. /* tag is a tag string displayed with the number */
  1075. /* */
  1076. /* This is a debug aid; the precise format of the string may change. */
  1077. /* ------------------------------------------------------------------ */
  1078. void decFloatShow(const decFloat *df, const char *tag) {
  1079. char hexbuf[DECBYTES*2+DECBYTES/4+1]; // NB blank after every fourth
  1080. char buff[DECSTRING]; // for value in decimal
  1081. Int i, j=0;
  1082. for (i=0; i<DECBYTES; i++) {
  1083. #if DECLITEND
  1084. sprintf(&hexbuf[j], "%02x", df->bytes[DECBYTES-1-i]);
  1085. #else
  1086. sprintf(&hexbuf[j], "%02x", df->bytes[i]);
  1087. #endif
  1088. j+=2;
  1089. // the next line adds blank (and terminator) after final pair, too
  1090. if ((i+1)%4==0) {strcpy(&hexbuf[j], " "); j++;}
  1091. }
  1092. decFloatToString(df, buff);
  1093. printf(">%s> %s [big-endian] %s\n", tag, hexbuf, buff);
  1094. return;
  1095. } // decFloatShow
  1096. #endif
  1097. /* ------------------------------------------------------------------ */
  1098. /* decFloatToBCD -- get sign, exponent, and BCD8 from a decFloat */
  1099. /* */
  1100. /* df is the source decFloat */
  1101. /* exp will be set to the unbiased exponent, q, or to a special */
  1102. /* value in the form returned by decFloatGetExponent */
  1103. /* bcdar is where DECPMAX bytes will be written, one BCD digit in */
  1104. /* each byte (BCD8 encoding); if df is a NaN the first byte will */
  1105. /* be zero, and if it is infinite they will all be zero */
  1106. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  1107. /* 0 otherwise) */
  1108. /* */
  1109. /* No error is possible, and no status will be set. */
  1110. /* ------------------------------------------------------------------ */
  1111. Int decFloatToBCD(const decFloat *df, Int *exp, uByte *bcdar) {
  1112. if (DFISINF(df)) {
  1113. memset(bcdar, 0, DECPMAX);
  1114. *exp=DFWORD(df, 0)&0x7e000000;
  1115. }
  1116. else {
  1117. GETCOEFF(df, bcdar); // use macro
  1118. if (DFISNAN(df)) {
  1119. bcdar[0]=0; // MSD needs correcting
  1120. *exp=DFWORD(df, 0)&0x7e000000;
  1121. }
  1122. else { // finite
  1123. *exp=GETEXPUN(df);
  1124. }
  1125. }
  1126. return GETSIGN(df);
  1127. } // decFloatToBCD
  1128. /* ------------------------------------------------------------------ */
  1129. /* decFloatToEngString -- conversion to numeric string, engineering */
  1130. /* */
  1131. /* df is the decFloat format number to convert */
  1132. /* string is the string where the result will be laid out */
  1133. /* */
  1134. /* string must be at least DECPMAX+9 characters (the worst case is */
  1135. /* "-0.00000nnn...nnn\0", which is as long as the exponent form when */
  1136. /* DECEMAXD<=4); this condition is asserted above */
  1137. /* */
  1138. /* No error is possible, and no status will be set */
  1139. /* ------------------------------------------------------------------ */
  1140. char * decFloatToEngString(const decFloat *df, char *string){
  1141. uInt msd; // coefficient MSD
  1142. Int exp; // exponent top two bits or full
  1143. uInt comb; // combination field
  1144. char *cstart; // coefficient start
  1145. char *c; // output pointer in string
  1146. char *s, *t; // .. (source, target)
  1147. Int pre, e; // work
  1148. const uByte *u; // ..
  1149. uInt uiwork; // for macros [one compiler needs
  1150. // volatile here to avoid bug, but
  1151. // that doubles execution time]
  1152. // Source words; macro handles endianness
  1153. uInt sourhi=DFWORD(df, 0); // word with sign
  1154. #if DECPMAX==16
  1155. uInt sourlo=DFWORD(df, 1);
  1156. #elif DECPMAX==34
  1157. uInt sourmh=DFWORD(df, 1);
  1158. uInt sourml=DFWORD(df, 2);
  1159. uInt sourlo=DFWORD(df, 3);
  1160. #endif
  1161. c=string; // where result will go
  1162. if (((Int)sourhi)<0) *c++='-'; // handle sign
  1163. comb=sourhi>>26; // sign+combination field
  1164. msd=DECCOMBMSD[comb]; // decode the combination field
  1165. exp=DECCOMBEXP[comb]; // ..
  1166. if (EXPISSPECIAL(exp)) { // special
  1167. if (exp==DECFLOAT_Inf) { // infinity
  1168. strcpy(c, "Inf");
  1169. strcpy(c+3, "inity");
  1170. return string; // easy
  1171. }
  1172. if (sourhi&0x02000000) *c++='s'; // sNaN
  1173. strcpy(c, "NaN"); // complete word
  1174. c+=3; // step past
  1175. // quick exit if the payload is zero
  1176. #if DECPMAX==7
  1177. if ((sourhi&0x000fffff)==0) return string;
  1178. #elif DECPMAX==16
  1179. if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;
  1180. #elif DECPMAX==34
  1181. if (sourlo==0 && sourml==0 && sourmh==0
  1182. && (sourhi&0x00003fff)==0) return string;
  1183. #endif
  1184. // otherwise drop through to add integer; set correct exp etc.
  1185. exp=0; msd=0; // setup for following code
  1186. }
  1187. else { // complete exponent; top two bits are in place
  1188. exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias
  1189. }
  1190. /* convert the digits of the significand to characters */
  1191. cstart=c; // save start of coefficient
  1192. if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit
  1193. // Decode the declets. After extracting each declet, it is
  1194. // decoded to a 4-uByte sequence by table lookup; the four uBytes
  1195. // are the three encoded BCD8 digits followed by a 1-byte length
  1196. // (significant digits, except that 000 has length 0). This allows
  1197. // us to left-align the first declet with non-zero content, then
  1198. // the remaining ones are full 3-char length. Fixed-length copies
  1199. // are used because variable-length memcpy causes a subroutine call
  1200. // in at least two compilers. (The copies are length 4 for speed
  1201. // and are safe because the last item in the array is of length
  1202. // three and has the length byte following.)
  1203. #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \
  1204. if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \
  1205. else if (*(u+3)) { \
  1206. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}
  1207. #if DECPMAX==7
  1208. dpd2char(sourhi>>10); // declet 1
  1209. dpd2char(sourhi); // declet 2
  1210. #elif DECPMAX==16
  1211. dpd2char(sourhi>>8); // declet 1
  1212. dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2
  1213. dpd2char(sourlo>>20); // declet 3
  1214. dpd2char(sourlo>>10); // declet 4
  1215. dpd2char(sourlo); // declet 5
  1216. #elif DECPMAX==34
  1217. dpd2char(sourhi>>4); // declet 1
  1218. dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2
  1219. dpd2char(sourmh>>16); // declet 3
  1220. dpd2char(sourmh>>6); // declet 4
  1221. dpd2char((sourmh<<4) | (sourml>>28)); // declet 5
  1222. dpd2char(sourml>>18); // declet 6
  1223. dpd2char(sourml>>8); // declet 7
  1224. dpd2char((sourml<<2) | (sourlo>>30)); // declet 8
  1225. dpd2char(sourlo>>20); // declet 9
  1226. dpd2char(sourlo>>10); // declet 10
  1227. dpd2char(sourlo); // declet 11
  1228. #endif
  1229. if (c==cstart) *c++='0'; // all zeros, empty -- make "0"
  1230. if (exp==0) { // integer or NaN case -- easy
  1231. *c='\0'; // terminate
  1232. return string;
  1233. }
  1234. /* non-0 exponent */
  1235. e=0; // assume no E
  1236. pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]
  1237. // [here, pre-exp is the digits count (==1 for zero)]
  1238. if (exp>0 || pre<-5) { // need exponential form
  1239. e=pre-1; // calculate E value
  1240. pre=1; // assume one digit before '.'
  1241. if (e!=0) { // engineering: may need to adjust
  1242. Int adj; // adjustment
  1243. // The C remainder operator is undefined for negative numbers, so
  1244. // a positive remainder calculation must be used here
  1245. if (e<0) {
  1246. adj=(-e)%3;
  1247. if (adj!=0) adj=3-adj;
  1248. }
  1249. else { // e>0
  1250. adj=e%3;
  1251. }
  1252. e=e-adj;
  1253. // if dealing with zero still produce an exponent which is a
  1254. // multiple of three, as expected, but there will only be the
  1255. // one zero before the E, still. Otherwise note the padding.
  1256. if (!DFISZERO(df)) pre+=adj;
  1257. else { // is zero
  1258. if (adj!=0) { // 0.00Esnn needed
  1259. e=e+3;
  1260. pre=-(2-adj);
  1261. }
  1262. } // zero
  1263. } // engineering adjustment
  1264. } // exponential form
  1265. // printf("e=%ld pre=%ld exp=%ld\n", (LI)e, (LI)pre, (LI)exp);
  1266. /* modify the coefficient, adding 0s, '.', and E+nn as needed */
  1267. if (pre>0) { // ddd.ddd (plain), perhaps with E
  1268. // or dd00 padding for engineering
  1269. char *dotat=cstart+pre;
  1270. if (dotat<c) { // if embedded dot needed...
  1271. // move by fours; there must be space for junk at the end
  1272. // because there is still space for exponent
  1273. s=dotat+ROUNDDOWN4(c-dotat); // source
  1274. t=s+1; // target
  1275. // open the gap [cannot use memcpy]
  1276. for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1277. *dotat='.';
  1278. c++; // length increased by one
  1279. } // need dot?
  1280. else for (; c<dotat; c++) *c='0'; // pad for engineering
  1281. } // pre>0
  1282. else {
  1283. /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (may have
  1284. E, but only for 0.00E+3 kind of case -- with plenty of spare
  1285. space in this case */
  1286. pre=-pre+2; // gap width, including "0."
  1287. t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point
  1288. // backoff if too far to the right
  1289. if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit
  1290. // now shift the entire coefficient to the right, being careful not
  1291. // to access to the left of string [cannot use memcpy]
  1292. for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1293. // for Quads and Singles there may be a character or two left...
  1294. s+=3; // where next would come from
  1295. for(; s>=cstart; s--, t--) *(t+3)=*(s);
  1296. // now have fill 0. through 0.00000; use overlaps to avoid tests
  1297. if (pre>=4) {
  1298. memcpy(cstart+pre-4, "0000", 4);
  1299. memcpy(cstart, "0.00", 4);
  1300. }
  1301. else { // 2 or 3
  1302. *(cstart+pre-1)='0';
  1303. memcpy(cstart, "0.", 2);
  1304. }
  1305. c+=pre; // to end
  1306. }
  1307. // finally add the E-part, if needed; it will never be 0, and has
  1308. // a maximum length of 3 or 4 digits (asserted above)
  1309. if (e!=0) {
  1310. memcpy(c, "E+", 2); // starts with E, assume +
  1311. c++;
  1312. if (e<0) {
  1313. *c='-'; // oops, need '-'
  1314. e=-e; // uInt, please
  1315. }
  1316. c++;
  1317. // Three-character exponents are easy; 4-character a little trickier
  1318. #if DECEMAXD<=3
  1319. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1320. // copy fixed 4 characters [is safe], starting at non-zero
  1321. // and with character mask to convert BCD to char
  1322. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);
  1323. c+=*(u+3); // bump pointer appropriately
  1324. #elif DECEMAXD==4
  1325. if (e<1000) { // 3 (or fewer) digits case
  1326. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1327. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1328. c+=*(u+3); // bump pointer appropriately
  1329. }
  1330. else { // 4-digits
  1331. Int thou=((e>>3)*1049)>>17; // e/1000
  1332. Int rem=e-(1000*thou); // e%1000
  1333. *c++=(char)('0'+(char)thou); // the thousands digit
  1334. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1335. UBFROMUI(c, UBTOUI(u)|CHARMASK);// copy fixed 3+1 characters [is safe]
  1336. c+=3; // bump pointer, always 3 digits
  1337. }
  1338. #endif
  1339. }
  1340. *c='\0'; // terminate
  1341. //printf("res %s\n", string);
  1342. return string;
  1343. } // decFloatToEngString
  1344. /* ------------------------------------------------------------------ */
  1345. /* decFloatToPacked -- convert decFloat to Packed decimal + exponent */
  1346. /* */
  1347. /* df is the source decFloat */
  1348. /* exp will be set to the unbiased exponent, q, or to a special */
  1349. /* value in the form returned by decFloatGetExponent */
  1350. /* packed is where DECPMAX nibbles will be written with the sign as */
  1351. /* final nibble (0x0c for +, 0x0d for -); a NaN has a first nibble */
  1352. /* of zero, and an infinity is all zeros. decDouble and decQuad */
  1353. /* have a additional leading zero nibble, leading to result */
  1354. /* lengths of 4, 9, and 18 bytes. */
  1355. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  1356. /* 0 otherwise) */
  1357. /* */
  1358. /* No error is possible, and no status will be set. */
  1359. /* ------------------------------------------------------------------ */
  1360. Int decFloatToPacked(const decFloat *df, Int *exp, uByte *packed) {
  1361. uByte bcdar[DECPMAX+2]; // work buffer
  1362. uByte *ip=bcdar, *op=packed; // work pointers
  1363. if (DFISINF(df)) {
  1364. memset(bcdar, 0, DECPMAX+2);
  1365. *exp=DECFLOAT_Inf;
  1366. }
  1367. else {
  1368. GETCOEFF(df, bcdar+1); // use macro
  1369. if (DFISNAN(df)) {
  1370. bcdar[1]=0; // MSD needs clearing
  1371. *exp=DFWORD(df, 0)&0x7e000000;
  1372. }
  1373. else { // finite
  1374. *exp=GETEXPUN(df);
  1375. }
  1376. }
  1377. // now pack; coefficient currently at bcdar+1
  1378. #if SINGLE
  1379. ip++; // ignore first byte
  1380. #else
  1381. *ip=0; // need leading zero
  1382. #endif
  1383. // set final byte to Packed BCD sign value
  1384. bcdar[DECPMAX+1]=(DFISSIGNED(df) ? DECPMINUS : DECPPLUS);
  1385. // pack an even number of bytes...
  1386. for (; op<packed+((DECPMAX+2)/2); op++, ip+=2) {
  1387. *op=(uByte)((*ip<<4)+*(ip+1));
  1388. }
  1389. return (bcdar[DECPMAX+1]==DECPMINUS ? DECFLOAT_Sign : 0);
  1390. } // decFloatToPacked
  1391. /* ------------------------------------------------------------------ */
  1392. /* decFloatToString -- conversion to numeric string */
  1393. /* */
  1394. /* df is the decFloat format number to convert */
  1395. /* string is the string where the result will be laid out */
  1396. /* */
  1397. /* string must be at least DECPMAX+9 characters (the worst case is */
  1398. /* "-0.00000nnn...nnn\0", which is as long as the exponent form when */
  1399. /* DECEMAXD<=4); this condition is asserted above */
  1400. /* */
  1401. /* No error is possible, and no status will be set */
  1402. /* ------------------------------------------------------------------ */
  1403. char * decFloatToString(const decFloat *df, char *string){
  1404. uInt msd; // coefficient MSD
  1405. Int exp; // exponent top two bits or full
  1406. uInt comb; // combination field
  1407. char *cstart; // coefficient start
  1408. char *c; // output pointer in string
  1409. char *s, *t; // .. (source, target)
  1410. Int pre, e; // work
  1411. const uByte *u; // ..
  1412. uInt uiwork; // for macros [one compiler needs
  1413. // volatile here to avoid bug, but
  1414. // that doubles execution time]
  1415. // Source words; macro handles endianness
  1416. uInt sourhi=DFWORD(df, 0); // word with sign
  1417. #if DECPMAX==16
  1418. uInt sourlo=DFWORD(df, 1);
  1419. #elif DECPMAX==34
  1420. uInt sourmh=DFWORD(df, 1);
  1421. uInt sourml=DFWORD(df, 2);
  1422. uInt sourlo=DFWORD(df, 3);
  1423. #endif
  1424. c=string; // where result will go
  1425. if (((Int)sourhi)<0) *c++='-'; // handle sign
  1426. comb=sourhi>>26; // sign+combination field
  1427. msd=DECCOMBMSD[comb]; // decode the combination field
  1428. exp=DECCOMBEXP[comb]; // ..
  1429. if (!EXPISSPECIAL(exp)) { // finite
  1430. // complete exponent; top two bits are in place
  1431. exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias
  1432. }
  1433. else { // IS special
  1434. if (exp==DECFLOAT_Inf) { // infinity
  1435. strcpy(c, "Infinity");
  1436. return string; // easy
  1437. }
  1438. if (sourhi&0x02000000) *c++='s'; // sNaN
  1439. strcpy(c, "NaN"); // complete word
  1440. c+=3; // step past
  1441. // quick exit if the payload is zero
  1442. #if DECPMAX==7
  1443. if ((sourhi&0x000fffff)==0) return string;
  1444. #elif DECPMAX==16
  1445. if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;
  1446. #elif DECPMAX==34
  1447. if (sourlo==0 && sourml==0 && sourmh==0
  1448. && (sourhi&0x00003fff)==0) return string;
  1449. #endif
  1450. // otherwise drop through to add integer; set correct exp etc.
  1451. exp=0; msd=0; // setup for following code
  1452. }
  1453. /* convert the digits of the significand to characters */
  1454. cstart=c; // save start of coefficient
  1455. if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit
  1456. // Decode the declets. After extracting each declet, it is
  1457. // decoded to a 4-uByte sequence by table lookup; the four uBytes
  1458. // are the three encoded BCD8 digits followed by a 1-byte length
  1459. // (significant digits, except that 000 has length 0). This allows
  1460. // us to left-align the first declet with non-zero content, then
  1461. // the remaining ones are full 3-char length. Fixed-length copies
  1462. // are used because variable-length memcpy causes a subroutine call
  1463. // in at least two compilers. (The copies are length 4 for speed
  1464. // and are safe because the last item in the array is of length
  1465. // three and has the length byte following.)
  1466. #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \
  1467. if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \
  1468. else if (*(u+3)) { \
  1469. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}
  1470. #if DECPMAX==7
  1471. dpd2char(sourhi>>10); // declet 1
  1472. dpd2char(sourhi); // declet 2
  1473. #elif DECPMAX==16
  1474. dpd2char(sourhi>>8); // declet 1
  1475. dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2
  1476. dpd2char(sourlo>>20); // declet 3
  1477. dpd2char(sourlo>>10); // declet 4
  1478. dpd2char(sourlo); // declet 5
  1479. #elif DECPMAX==34
  1480. dpd2char(sourhi>>4); // declet 1
  1481. dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2
  1482. dpd2char(sourmh>>16); // declet 3
  1483. dpd2char(sourmh>>6); // declet 4
  1484. dpd2char((sourmh<<4) | (sourml>>28)); // declet 5
  1485. dpd2char(sourml>>18); // declet 6
  1486. dpd2char(sourml>>8); // declet 7
  1487. dpd2char((sourml<<2) | (sourlo>>30)); // declet 8
  1488. dpd2char(sourlo>>20); // declet 9
  1489. dpd2char(sourlo>>10); // declet 10
  1490. dpd2char(sourlo); // declet 11
  1491. #endif
  1492. if (c==cstart) *c++='0'; // all zeros, empty -- make "0"
  1493. //[This fast path is valid but adds 3-5 cycles to worst case length]
  1494. //if (exp==0) { // integer or NaN case -- easy
  1495. // *c='\0'; // terminate
  1496. // return string;
  1497. // }
  1498. e=0; // assume no E
  1499. pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]
  1500. // [here, pre-exp is the digits count (==1 for zero)]
  1501. if (exp>0 || pre<-5) { // need exponential form
  1502. e=pre-1; // calculate E value
  1503. pre=1; // assume one digit before '.'
  1504. } // exponential form
  1505. /* modify the coefficient, adding 0s, '.', and E+nn as needed */
  1506. if (pre>0) { // ddd.ddd (plain), perhaps with E
  1507. char *dotat=cstart+pre;
  1508. if (dotat<c) { // if embedded dot needed...
  1509. // [memmove is a disaster, here]
  1510. // move by fours; there must be space for junk at the end
  1511. // because exponent is still possible
  1512. s=dotat+ROUNDDOWN4(c-dotat); // source
  1513. t=s+1; // target
  1514. // open the gap [cannot use memcpy]
  1515. for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1516. *dotat='.';
  1517. c++; // length increased by one
  1518. } // need dot?
  1519. // finally add the E-part, if needed; it will never be 0, and has
  1520. // a maximum length of 3 or 4 digits (asserted above)
  1521. if (e!=0) {
  1522. memcpy(c, "E+", 2); // starts with E, assume +
  1523. c++;
  1524. if (e<0) {
  1525. *c='-'; // oops, need '-'
  1526. e=-e; // uInt, please
  1527. }
  1528. c++;
  1529. // Three-character exponents are easy; 4-character a little trickier
  1530. #if DECEMAXD<=3
  1531. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1532. // copy fixed 4 characters [is safe], starting at non-zero
  1533. // and with character mask to convert BCD to char
  1534. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);
  1535. c+=*(u+3); // bump pointer appropriately
  1536. #elif DECEMAXD==4
  1537. if (e<1000) { // 3 (or fewer) digits case
  1538. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1539. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1540. c+=*(u+3); // bump pointer appropriately
  1541. }
  1542. else { // 4-digits
  1543. Int thou=((e>>3)*1049)>>17; // e/1000
  1544. Int rem=e-(1000*thou); // e%1000
  1545. *c++=(char)('0'+(char)thou); // the thousands digit
  1546. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1547. UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]
  1548. c+=3; // bump pointer, always 3 digits
  1549. }
  1550. #endif
  1551. }
  1552. *c='\0'; // add terminator
  1553. //printf("res %s\n", string);
  1554. return string;
  1555. } // pre>0
  1556. /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
  1557. // Surprisingly, this is close to being the worst-case path, so the
  1558. // shift is done by fours; this is a little tricky because the
  1559. // rightmost character to be written must not be beyond where the
  1560. // rightmost terminator could be -- so backoff to not touch
  1561. // terminator position if need be (this can make exact alignments
  1562. // for full Doubles, but in some cases needs care not to access too
  1563. // far to the left)
  1564. pre=-pre+2; // gap width, including "0."
  1565. t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point
  1566. // backoff if too far to the right
  1567. if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit
  1568. // now shift the entire coefficient to the right, being careful not
  1569. // to access to the left of string [cannot use memcpy]
  1570. for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1571. // for Quads and Singles there may be a character or two left...
  1572. s+=3; // where next would come from
  1573. for(; s>=cstart; s--, t--) *(t+3)=*(s);
  1574. // now have fill 0. through 0.00000; use overlaps to avoid tests
  1575. if (pre>=4) {
  1576. memcpy(cstart+pre-4, "0000", 4);
  1577. memcpy(cstart, "0.00", 4);
  1578. }
  1579. else { // 2 or 3
  1580. *(cstart+pre-1)='0';
  1581. memcpy(cstart, "0.", 2);
  1582. }
  1583. *(c+pre)='\0'; // terminate
  1584. return string;
  1585. } // decFloatToString
  1586. /* ------------------------------------------------------------------ */
  1587. /* decFloatToWider -- conversion to next-wider format */
  1588. /* */
  1589. /* source is the decFloat format number which gets the result of */
  1590. /* the conversion */
  1591. /* wider is the decFloatWider format number which will be narrowed */
  1592. /* returns wider */
  1593. /* */
  1594. /* Widening is always exact; no status is set (sNaNs are copied and */
  1595. /* do not signal). The result will be canonical if the source is, */
  1596. /* and may or may not be if the source is not. */
  1597. /* ------------------------------------------------------------------ */
  1598. // widening is not possible for decQuad format numbers; simply omit
  1599. #if !QUAD
  1600. decFloatWider * decFloatToWider(const decFloat *source, decFloatWider *wider) {
  1601. uInt msd;
  1602. /* Construct and copy the sign word */
  1603. if (DFISSPECIAL(source)) {
  1604. // copy sign, combination, and first bit of exponent (sNaN selector)
  1605. DFWWORD(wider, 0)=DFWORD(source, 0)&0xfe000000;
  1606. msd=0;
  1607. }
  1608. else { // is finite number
  1609. uInt exp=GETEXPUN(source)+DECWBIAS; // get unbiased exponent and rebias
  1610. uInt code=(exp>>DECWECONL)<<29; // set two bits of exp [msd=0]
  1611. code|=(exp<<(32-6-DECWECONL)) & 0x03ffffff; // add exponent continuation
  1612. code|=DFWORD(source, 0)&0x80000000; // add sign
  1613. DFWWORD(wider, 0)=code; // .. and place top word in wider
  1614. msd=GETMSD(source); // get source coefficient MSD [0-9]
  1615. }
  1616. /* Copy the coefficient and clear any 'unused' words to left */
  1617. #if SINGLE
  1618. DFWWORD(wider, 1)=(DFWORD(source, 0)&0x000fffff)|(msd<<20);
  1619. #elif DOUBLE
  1620. DFWWORD(wider, 2)=(DFWORD(source, 0)&0x0003ffff)|(msd<<18);
  1621. DFWWORD(wider, 3)=DFWORD(source, 1);
  1622. DFWWORD(wider, 1)=0;
  1623. #endif
  1624. return wider;
  1625. } // decFloatToWider
  1626. #endif
  1627. /* ------------------------------------------------------------------ */
  1628. /* decFloatVersion -- return package version string */
  1629. /* */
  1630. /* returns a constant string describing this package */
  1631. /* ------------------------------------------------------------------ */
  1632. const char *decFloatVersion(void) {
  1633. return DECVERSION;
  1634. } // decFloatVersion
  1635. /* ------------------------------------------------------------------ */
  1636. /* decFloatZero -- set to canonical (integer) zero */
  1637. /* */
  1638. /* df is the decFloat format number to integer +0 (q=0, c=+0) */
  1639. /* returns df */
  1640. /* */
  1641. /* No error is possible, and no status can be set. */
  1642. /* ------------------------------------------------------------------ */
  1643. decFloat * decFloatZero(decFloat *df){
  1644. DFWORD(df, 0)=ZEROWORD; // set appropriate top word
  1645. #if DOUBLE || QUAD
  1646. DFWORD(df, 1)=0;
  1647. #if QUAD
  1648. DFWORD(df, 2)=0;
  1649. DFWORD(df, 3)=0;
  1650. #endif
  1651. #endif
  1652. // decFloatShow(df, "zero");
  1653. return df;
  1654. } // decFloatZero
  1655. /* ------------------------------------------------------------------ */
  1656. /* Private generic function (not format-specific) for development use */
  1657. /* ------------------------------------------------------------------ */
  1658. // This is included once only, for all to use
  1659. #if QUAD && (DECCHECK || DECTRACE)
  1660. /* ---------------------------------------------------------------- */
  1661. /* decShowNum -- display bcd8 number in debug form */
  1662. /* */
  1663. /* num is the bcdnum to display */
  1664. /* tag is a string to label the display */
  1665. /* ---------------------------------------------------------------- */
  1666. void decShowNum(const bcdnum *num, const char *tag) {
  1667. const char *csign="+"; // sign character
  1668. uByte *ub; // work
  1669. uInt uiwork; // for macros
  1670. if (num->sign==DECFLOAT_Sign) csign="-";
  1671. printf(">%s> ", tag);
  1672. if (num->exponent==DECFLOAT_Inf) printf("%sInfinity", csign);
  1673. else if (num->exponent==DECFLOAT_qNaN) printf("%sqNaN", csign);
  1674. else if (num->exponent==DECFLOAT_sNaN) printf("%ssNaN", csign);
  1675. else { // finite
  1676. char qbuf[10]; // for right-aligned q
  1677. char *c; // work
  1678. const uByte *u; // ..
  1679. Int e=num->exponent; // .. exponent
  1680. strcpy(qbuf, "q=");
  1681. c=&qbuf[2]; // where exponent will go
  1682. // lay out the exponent
  1683. if (e<0) {
  1684. *c++='-'; // add '-'
  1685. e=-e; // uInt, please
  1686. }
  1687. #if DECEMAXD>4
  1688. #error Exponent form is too long for ShowNum to lay out
  1689. #endif
  1690. if (e==0) *c++='0'; // 0-length case
  1691. else if (e<1000) { // 3 (or fewer) digits case
  1692. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1693. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1694. c+=*(u+3); // bump pointer appropriately
  1695. }
  1696. else { // 4-digits
  1697. Int thou=((e>>3)*1049)>>17; // e/1000
  1698. Int rem=e-(1000*thou); // e%1000
  1699. *c++=(char)('0'+(char)thou); // the thousands digit
  1700. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1701. UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]
  1702. c+=3; // bump pointer, always 3 digits
  1703. }
  1704. *c='\0'; // add terminator
  1705. printf("%7s c=%s", qbuf, csign);
  1706. }
  1707. if (!EXPISSPECIAL(num->exponent) || num->msd!=num->lsd || *num->lsd!=0) {
  1708. for (ub=num->msd; ub<=num->lsd; ub++) { // coefficient...
  1709. printf("%1x", *ub);
  1710. if ((num->lsd-ub)%3==0 && ub!=num->lsd) printf(" "); // 4-space
  1711. }
  1712. }
  1713. printf("\n");
  1714. } // decShowNum
  1715. #endif