decCommon.c 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835
  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. #if DECCHECK
  225. Int clen=ulsd-umsd+1;
  226. #if QUAD
  227. #define COEXTRA 2 // extra-long coefficent
  228. #else
  229. #define COEXTRA 0
  230. #endif
  231. if (clen<1 || clen>DECPMAX*3+2+COEXTRA)
  232. printf("decFinalize: suspect coefficient [length=%ld]\n", (LI)clen);
  233. if (num->sign!=0 && num->sign!=DECFLOAT_Sign)
  234. printf("decFinalize: bad sign [%08lx]\n", (LI)num->sign);
  235. if (!EXPISSPECIAL(num->exponent)
  236. && (num->exponent>1999999999 || num->exponent<-1999999999))
  237. printf("decFinalize: improbable exponent [%ld]\n", (LI)num->exponent);
  238. // decShowNum(num, "final");
  239. #endif
  240. // A special will have an 'exponent' which is very positive and a
  241. // coefficient < DECPMAX
  242. length=(uInt)(ulsd-umsd+1); // coefficient length
  243. if (!NUMISSPECIAL(num)) {
  244. Int drop; // digits to be dropped
  245. // skip leading insignificant zeros to calculate an exact length
  246. // [this is quite expensive]
  247. if (*umsd==0) {
  248. for (; umsd+3<ulsd && UBTOUI(umsd)==0;) umsd+=4;
  249. for (; *umsd==0 && umsd<ulsd;) umsd++;
  250. length=ulsd-umsd+1; // recalculate
  251. }
  252. drop=MAXI(length-DECPMAX, DECQTINY-num->exponent);
  253. // drop can now be > digits for bottom-clamp (subnormal) cases
  254. if (drop>0) { // rounding needed
  255. // (decFloatQuantize has very similar code to this, so any
  256. // changes may need to be made there, too)
  257. uByte *roundat; // -> re-round digit
  258. uByte reround; // reround value
  259. // printf("Rounding; drop=%ld\n", (LI)drop);
  260. num->exponent+=drop; // always update exponent
  261. // Three cases here:
  262. // 1. new LSD is in coefficient (almost always)
  263. // 2. new LSD is digit to left of coefficient (so MSD is
  264. // round-for-reround digit)
  265. // 3. new LSD is to left of case 2 (whole coefficient is sticky)
  266. // [duplicate check-stickies code to save a test]
  267. // [by-digit check for stickies as runs of zeros are rare]
  268. if (drop<length) { // NB lengths not addresses
  269. roundat=umsd+length-drop;
  270. reround=*roundat;
  271. for (ub=roundat+1; ub<=ulsd; ub++) {
  272. if (*ub!=0) { // non-zero to be discarded
  273. reround=DECSTICKYTAB[reround]; // apply sticky bit
  274. break; // [remainder don't-care]
  275. }
  276. } // check stickies
  277. ulsd=roundat-1; // new LSD
  278. }
  279. else { // edge case
  280. if (drop==length) {
  281. roundat=umsd;
  282. reround=*roundat;
  283. }
  284. else {
  285. roundat=umsd-1;
  286. reround=0;
  287. }
  288. for (ub=roundat+1; ub<=ulsd; ub++) {
  289. if (*ub!=0) { // non-zero to be discarded
  290. reround=DECSTICKYTAB[reround]; // apply sticky bit
  291. break; // [remainder don't-care]
  292. }
  293. } // check stickies
  294. *umsd=0; // coefficient is a 0
  295. ulsd=umsd; // ..
  296. }
  297. if (reround!=0) { // discarding non-zero
  298. uInt bump=0;
  299. set->status|=DEC_Inexact;
  300. // if adjusted exponent [exp+digits-1] is < EMIN then num is
  301. // subnormal -- so raise Underflow
  302. if (num->exponent<DECEMIN && (num->exponent+(ulsd-umsd+1)-1)<DECEMIN)
  303. set->status|=DEC_Underflow;
  304. // next decide whether increment of the coefficient is needed
  305. if (set->round==DEC_ROUND_HALF_EVEN) { // fastpath slowest case
  306. if (reround>5) bump=1; // >0.5 goes up
  307. else if (reround==5) // exactly 0.5000 ..
  308. bump=*ulsd & 0x01; // .. up iff [new] lsd is odd
  309. } // r-h-e
  310. else switch (set->round) {
  311. case DEC_ROUND_DOWN: {
  312. // no change
  313. break;} // r-d
  314. case DEC_ROUND_HALF_DOWN: {
  315. if (reround>5) bump=1;
  316. break;} // r-h-d
  317. case DEC_ROUND_HALF_UP: {
  318. if (reround>=5) bump=1;
  319. break;} // r-h-u
  320. case DEC_ROUND_UP: {
  321. if (reround>0) bump=1;
  322. break;} // r-u
  323. case DEC_ROUND_CEILING: {
  324. // same as _UP for positive numbers, and as _DOWN for negatives
  325. if (!num->sign && reround>0) bump=1;
  326. break;} // r-c
  327. case DEC_ROUND_FLOOR: {
  328. // same as _UP for negative numbers, and as _DOWN for positive
  329. // [negative reround cannot occur on 0]
  330. if (num->sign && reround>0) bump=1;
  331. break;} // r-f
  332. case DEC_ROUND_05UP: {
  333. if (reround>0) { // anything out there is 'sticky'
  334. // bump iff lsd=0 or 5; this cannot carry so it could be
  335. // effected immediately with no bump -- but the code
  336. // is clearer if this is done the same way as the others
  337. if (*ulsd==0 || *ulsd==5) bump=1;
  338. }
  339. break;} // r-r
  340. default: { // e.g., DEC_ROUND_MAX
  341. set->status|=DEC_Invalid_context;
  342. #if DECCHECK
  343. printf("Unknown rounding mode: %ld\n", (LI)set->round);
  344. #endif
  345. break;}
  346. } // switch (not r-h-e)
  347. // printf("ReRound: %ld bump: %ld\n", (LI)reround, (LI)bump);
  348. if (bump!=0) { // need increment
  349. // increment the coefficient; this might end up with 1000...
  350. // (after the all nines case)
  351. ub=ulsd;
  352. for(; ub-3>=umsd && UBTOUI(ub-3)==0x09090909; ub-=4) {
  353. UBFROMUI(ub-3, 0); // to 00000000
  354. }
  355. // [note ub could now be to left of msd, and it is not safe
  356. // to write to the the left of the msd]
  357. // now at most 3 digits left to non-9 (usually just the one)
  358. for (; ub>=umsd; *ub=0, ub--) {
  359. if (*ub==9) continue; // carry
  360. *ub+=1;
  361. break;
  362. }
  363. if (ub<umsd) { // had all-nines
  364. *umsd=1; // coefficient to 1000...
  365. // usually the 1000... coefficient can be used as-is
  366. if ((ulsd-umsd+1)==DECPMAX) {
  367. num->exponent++;
  368. }
  369. else {
  370. // if coefficient is shorter than Pmax then num is
  371. // subnormal, so extend it; this is safe as drop>0
  372. // (or, if the coefficient was supplied above, it could
  373. // not be 9); this may make the result normal.
  374. ulsd++;
  375. *ulsd=0;
  376. // [exponent unchanged]
  377. #if DECCHECK
  378. if (num->exponent!=DECQTINY) // sanity check
  379. printf("decFinalize: bad all-nines extend [^%ld, %ld]\n",
  380. (LI)num->exponent, (LI)(ulsd-umsd+1));
  381. #endif
  382. } // subnormal extend
  383. } // had all-nines
  384. } // bump needed
  385. } // inexact rounding
  386. length=ulsd-umsd+1; // recalculate (may be <DECPMAX)
  387. } // need round (drop>0)
  388. // The coefficient will now fit and has final length unless overflow
  389. // decShowNum(num, "rounded");
  390. // if exponent is >=emax may have to clamp, overflow, or fold-down
  391. if (num->exponent>DECEMAX-(DECPMAX-1)) { // is edge case
  392. // printf("overflow checks...\n");
  393. if (*ulsd==0 && ulsd==umsd) { // have zero
  394. num->exponent=DECEMAX-(DECPMAX-1); // clamp to max
  395. }
  396. else if ((num->exponent+length-1)>DECEMAX) { // > Nmax
  397. // Overflow -- these could go straight to encoding, here, but
  398. // instead num is adjusted to keep the code cleaner
  399. Flag needmax=0; // 1 for finite result
  400. set->status|=(DEC_Overflow | DEC_Inexact);
  401. switch (set->round) {
  402. case DEC_ROUND_DOWN: {
  403. needmax=1; // never Infinity
  404. break;} // r-d
  405. case DEC_ROUND_05UP: {
  406. needmax=1; // never Infinity
  407. break;} // r-05
  408. case DEC_ROUND_CEILING: {
  409. if (num->sign) needmax=1; // Infinity iff non-negative
  410. break;} // r-c
  411. case DEC_ROUND_FLOOR: {
  412. if (!num->sign) needmax=1; // Infinity iff negative
  413. break;} // r-f
  414. default: break; // Infinity in all other cases
  415. }
  416. if (!needmax) { // easy .. set Infinity
  417. num->exponent=DECFLOAT_Inf;
  418. *umsd=0; // be clean: coefficient to 0
  419. ulsd=umsd; // ..
  420. }
  421. else { // return Nmax
  422. umsd=allnines; // use constant array
  423. ulsd=allnines+DECPMAX-1;
  424. num->exponent=DECEMAX-(DECPMAX-1);
  425. }
  426. }
  427. else { // no overflow but non-zero and may have to fold-down
  428. Int shift=num->exponent-(DECEMAX-(DECPMAX-1));
  429. if (shift>0) { // fold-down needed
  430. // fold down needed; must copy to buffer in order to pad
  431. // with zeros safely; fortunately this is not the worst case
  432. // path because cannot have had a round
  433. uByte buffer[ROUNDUP(DECPMAX+3, 4)]; // [+3 allows uInt padding]
  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. if (*cfirst=='.') cfirst++; // step past dot at start
  845. if (*cfirst=='0') { // [cfirst always -> digit]
  846. for (; cfirst<clast; cfirst++) {
  847. if (*cfirst!='0') { // non-zero found
  848. if (*cfirst=='.') continue; // [ignore]
  849. break; // done
  850. }
  851. digits--; // 0 stripped
  852. } // cfirst
  853. } // at least one leading 0
  854. // the coefficient is now as short as possible, but may still
  855. // be too long; copy up to Pmax+1 digits to the buffer, then
  856. // just record any non-zeros (set round-for-reround digit)
  857. for (c=cfirst; c<=clast && ub<=buffer+DECPMAX; c++) {
  858. // (see commentary just above)
  859. if (c<=clast-3 // safe for four
  860. && (UBTOUI(c)&0xf0f0f0f0)==CHARMASK) { // four digits
  861. UBFROMUI(ub, UBTOUI(c)&0x0f0f0f0f); // to BCD8
  862. ub+=4;
  863. c+=3; // [will become 4]
  864. continue;
  865. }
  866. if (*c=='.') continue; // [ignore]
  867. *ub++=(uByte)(*c-'0');
  868. }
  869. ub--; // -> LSD
  870. for (; c<=clast; c++) { // inspect remaining chars
  871. if (*c!='0') { // sticky bit needed
  872. if (*c=='.') continue; // [ignore]
  873. *ub=DECSTICKYTAB[*ub]; // update round-for-reround
  874. break; // no need to look at more
  875. }
  876. }
  877. num.lsd=ub; // record LSD
  878. // adjust exponent for dropped digits
  879. num.exponent+=digits-(Int)(ub-buffer+1);
  880. } // too long for buffer
  881. } // digits and/or dot
  882. else { // no digits or dot were found
  883. // only Infinities and NaNs are allowed, here
  884. if (*c=='\0') break; // nothing there is bad
  885. buffer[0]=0; // default a coefficient of 0
  886. num.lsd=buffer; // ..
  887. if (decBiStr(c, "infinity", "INFINITY")
  888. || decBiStr(c, "inf", "INF")) num.exponent=DECFLOAT_Inf;
  889. else { // should be a NaN
  890. num.exponent=DECFLOAT_qNaN; // assume quiet NaN
  891. if (*c=='s' || *c=='S') { // probably an sNaN
  892. num.exponent=DECFLOAT_sNaN; // effect the 's'
  893. c++; // and step over it
  894. }
  895. if (*c!='N' && *c!='n') break; // check caseless "NaN"
  896. c++;
  897. if (*c!='a' && *c!='A') break; // ..
  898. c++;
  899. if (*c!='N' && *c!='n') break; // ..
  900. c++;
  901. // now either nothing, or nnnn payload (no dots), expected
  902. // -> start of integer, and skip leading 0s [including plain 0]
  903. for (cfirst=c; *cfirst=='0';) cfirst++;
  904. if (*cfirst!='\0') { // not empty or all-0, payload
  905. // payload found; check all valid digits and copy to buffer as bcd8
  906. ub=buffer;
  907. for (c=cfirst;; c++, ub++) {
  908. if ((unsigned)(*c-'0')>9) break; // quit if not 0-9
  909. if (c-cfirst==DECPMAX-1) break; // too many digits
  910. *ub=(uByte)(*c-'0'); // good bcd8
  911. }
  912. if (*c!='\0') break; // not all digits, or too many
  913. num.lsd=ub-1; // record new LSD
  914. }
  915. } // NaN or sNaN
  916. error=0; // syntax is OK
  917. } // digits=0 (special expected)
  918. break; // drop out
  919. } // [for(;;) once-loop]
  920. // decShowNum(&num, "fromStr");
  921. if (error!=0) {
  922. set->status|=error;
  923. num.exponent=DECFLOAT_qNaN; // set up quiet NaN
  924. num.sign=0; // .. with 0 sign
  925. buffer[0]=0; // .. and coefficient
  926. num.lsd=buffer; // ..
  927. // decShowNum(&num, "oops");
  928. }
  929. // decShowNum(&num, "dffs");
  930. decFinalize(result, &num, set); // round, check, and lay out
  931. // decFloatShow(result, "fromString");
  932. return result;
  933. } // decFloatFromString
  934. /* ------------------------------------------------------------------ */
  935. /* decFloatFromWider -- conversion from next-wider format */
  936. /* */
  937. /* result is the decFloat format number which gets the result of */
  938. /* the conversion */
  939. /* wider is the decFloatWider format number which will be narrowed */
  940. /* set is the context */
  941. /* returns result */
  942. /* */
  943. /* Narrowing can cause rounding, overflow, etc., but not Invalid */
  944. /* operation (sNaNs are copied and do not signal). */
  945. /* ------------------------------------------------------------------ */
  946. // narrow-to is not possible for decQuad format numbers; simply omit
  947. #if !QUAD
  948. decFloat * decFloatFromWider(decFloat *result, const decFloatWider *wider,
  949. decContext *set) {
  950. bcdnum num; // collects data for finishing
  951. uByte bcdar[DECWPMAX]; // room for wider coefficient
  952. uInt widerhi=DFWWORD(wider, 0); // top word
  953. Int exp;
  954. GETWCOEFF(wider, bcdar);
  955. num.msd=bcdar; // MSD is here always
  956. num.lsd=bcdar+DECWPMAX-1; // LSD is here always
  957. num.sign=widerhi&0x80000000; // extract sign [DECFLOAT_Sign=Neg]
  958. // decode the wider combination field to exponent
  959. exp=DECCOMBWEXP[widerhi>>26]; // decode from wider combination field
  960. // if it is a special there's nothing to do unless sNaN; if it's
  961. // finite then add the (wider) exponent continuation and unbias
  962. if (EXPISSPECIAL(exp)) exp=widerhi&0x7e000000; // include sNaN selector
  963. else exp+=GETWECON(wider)-DECWBIAS;
  964. num.exponent=exp;
  965. // decShowNum(&num, "dffw");
  966. return decFinalize(result, &num, set);// round, check, and lay out
  967. } // decFloatFromWider
  968. #endif
  969. /* ------------------------------------------------------------------ */
  970. /* decFloatGetCoefficient -- get coefficient as BCD8 */
  971. /* */
  972. /* df is the decFloat from which to extract the coefficient */
  973. /* bcdar is where DECPMAX bytes will be written, one BCD digit in */
  974. /* each byte (BCD8 encoding); if df is a NaN the first byte will */
  975. /* be zero, and if it is infinite they will all be zero */
  976. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  977. /* 0 otherwise) */
  978. /* */
  979. /* No error is possible, and no status will be set. If df is a */
  980. /* special value the array is set to zeros (for Infinity) or to the */
  981. /* payload of a qNaN or sNaN. */
  982. /* ------------------------------------------------------------------ */
  983. Int decFloatGetCoefficient(const decFloat *df, uByte *bcdar) {
  984. if (DFISINF(df)) memset(bcdar, 0, DECPMAX);
  985. else {
  986. GETCOEFF(df, bcdar); // use macro
  987. if (DFISNAN(df)) bcdar[0]=0; // MSD needs correcting
  988. }
  989. return GETSIGN(df);
  990. } // decFloatGetCoefficient
  991. /* ------------------------------------------------------------------ */
  992. /* decFloatGetExponent -- get unbiased exponent */
  993. /* */
  994. /* df is the decFloat from which to extract the exponent */
  995. /* returns the exponent, q. */
  996. /* */
  997. /* No error is possible, and no status will be set. If df is a */
  998. /* special value the first seven bits of the decFloat are returned, */
  999. /* left adjusted and with the first (sign) bit set to 0 (followed by */
  1000. /* 25 0 bits). e.g., -sNaN would return 0x7e000000 (DECFLOAT_sNaN). */
  1001. /* ------------------------------------------------------------------ */
  1002. Int decFloatGetExponent(const decFloat *df) {
  1003. if (DFISSPECIAL(df)) return DFWORD(df, 0)&0x7e000000;
  1004. return GETEXPUN(df);
  1005. } // decFloatGetExponent
  1006. /* ------------------------------------------------------------------ */
  1007. /* decFloatSetCoefficient -- set coefficient from BCD8 */
  1008. /* */
  1009. /* df is the target decFloat (and source of exponent/special value) */
  1010. /* bcdar holds DECPMAX digits to set the coefficient from, one */
  1011. /* digit in each byte (BCD8 encoding); the first (MSD) is ignored */
  1012. /* if df is a NaN; all are ignored if df is infinite. */
  1013. /* sig is DECFLOAT_Sign to set the sign bit, 0 otherwise */
  1014. /* returns df, which will be canonical */
  1015. /* */
  1016. /* No error is possible, and no status will be set. */
  1017. /* ------------------------------------------------------------------ */
  1018. decFloat * decFloatSetCoefficient(decFloat *df, const uByte *bcdar,
  1019. Int sig) {
  1020. uInt exp; // for exponent
  1021. uByte bcdzero[DECPMAX]; // for infinities
  1022. // Exponent/special code is extracted from df
  1023. if (DFISSPECIAL(df)) {
  1024. exp=DFWORD(df, 0)&0x7e000000;
  1025. if (DFISINF(df)) {
  1026. memset(bcdzero, 0, DECPMAX);
  1027. return decFloatFromBCD(df, exp, bcdzero, sig);
  1028. }
  1029. }
  1030. else exp=GETEXPUN(df);
  1031. return decFloatFromBCD(df, exp, bcdar, sig);
  1032. } // decFloatSetCoefficient
  1033. /* ------------------------------------------------------------------ */
  1034. /* decFloatSetExponent -- set exponent or special value */
  1035. /* */
  1036. /* df is the target decFloat (and source of coefficient/payload) */
  1037. /* set is the context for reporting status */
  1038. /* exp is the unbiased exponent, q, or a special value in the form */
  1039. /* returned by decFloatGetExponent */
  1040. /* returns df, which will be canonical */
  1041. /* */
  1042. /* No error is possible, but Overflow or Underflow might occur. */
  1043. /* ------------------------------------------------------------------ */
  1044. decFloat * decFloatSetExponent(decFloat *df, decContext *set, Int exp) {
  1045. uByte bcdcopy[DECPMAX]; // for coefficient
  1046. bcdnum num; // work
  1047. num.exponent=exp;
  1048. num.sign=decFloatGetCoefficient(df, bcdcopy); // extract coefficient
  1049. if (DFISSPECIAL(df)) { // MSD or more needs correcting
  1050. if (DFISINF(df)) memset(bcdcopy, 0, DECPMAX);
  1051. bcdcopy[0]=0;
  1052. }
  1053. num.msd=bcdcopy;
  1054. num.lsd=bcdcopy+DECPMAX-1;
  1055. return decFinalize(df, &num, set);
  1056. } // decFloatSetExponent
  1057. /* ------------------------------------------------------------------ */
  1058. /* decFloatRadix -- returns the base (10) */
  1059. /* */
  1060. /* df is any decFloat of this format */
  1061. /* ------------------------------------------------------------------ */
  1062. uInt decFloatRadix(const decFloat *df) {
  1063. if (df) return 10; // to placate compiler
  1064. return 10;
  1065. } // decFloatRadix
  1066. /* The following function is not available if DECPRINT=0 */
  1067. #if DECPRINT
  1068. /* ------------------------------------------------------------------ */
  1069. /* decFloatShow -- printf a decFloat in hexadecimal and decimal */
  1070. /* df is the decFloat to show */
  1071. /* tag is a tag string displayed with the number */
  1072. /* */
  1073. /* This is a debug aid; the precise format of the string may change. */
  1074. /* ------------------------------------------------------------------ */
  1075. void decFloatShow(const decFloat *df, const char *tag) {
  1076. char hexbuf[DECBYTES*2+DECBYTES/4+1]; // NB blank after every fourth
  1077. char buff[DECSTRING]; // for value in decimal
  1078. Int i, j=0;
  1079. for (i=0; i<DECBYTES; i++) {
  1080. #if DECLITEND
  1081. sprintf(&hexbuf[j], "%02x", df->bytes[DECBYTES-1-i]);
  1082. #else
  1083. sprintf(&hexbuf[j], "%02x", df->bytes[i]);
  1084. #endif
  1085. j+=2;
  1086. // the next line adds blank (and terminator) after final pair, too
  1087. if ((i+1)%4==0) {strcpy(&hexbuf[j], " "); j++;}
  1088. }
  1089. decFloatToString(df, buff);
  1090. printf(">%s> %s [big-endian] %s\n", tag, hexbuf, buff);
  1091. return;
  1092. } // decFloatShow
  1093. #endif
  1094. /* ------------------------------------------------------------------ */
  1095. /* decFloatToBCD -- get sign, exponent, and BCD8 from a decFloat */
  1096. /* */
  1097. /* df is the source decFloat */
  1098. /* exp will be set to the unbiased exponent, q, or to a special */
  1099. /* value in the form returned by decFloatGetExponent */
  1100. /* bcdar is where DECPMAX bytes will be written, one BCD digit in */
  1101. /* each byte (BCD8 encoding); if df is a NaN the first byte will */
  1102. /* be zero, and if it is infinite they will all be zero */
  1103. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  1104. /* 0 otherwise) */
  1105. /* */
  1106. /* No error is possible, and no status will be set. */
  1107. /* ------------------------------------------------------------------ */
  1108. Int decFloatToBCD(const decFloat *df, Int *exp, uByte *bcdar) {
  1109. if (DFISINF(df)) {
  1110. memset(bcdar, 0, DECPMAX);
  1111. *exp=DFWORD(df, 0)&0x7e000000;
  1112. }
  1113. else {
  1114. GETCOEFF(df, bcdar); // use macro
  1115. if (DFISNAN(df)) {
  1116. bcdar[0]=0; // MSD needs correcting
  1117. *exp=DFWORD(df, 0)&0x7e000000;
  1118. }
  1119. else { // finite
  1120. *exp=GETEXPUN(df);
  1121. }
  1122. }
  1123. return GETSIGN(df);
  1124. } // decFloatToBCD
  1125. /* ------------------------------------------------------------------ */
  1126. /* decFloatToEngString -- conversion to numeric string, engineering */
  1127. /* */
  1128. /* df is the decFloat format number to convert */
  1129. /* string is the string where the result will be laid out */
  1130. /* */
  1131. /* string must be at least DECPMAX+9 characters (the worst case is */
  1132. /* "-0.00000nnn...nnn\0", which is as long as the exponent form when */
  1133. /* DECEMAXD<=4); this condition is asserted above */
  1134. /* */
  1135. /* No error is possible, and no status will be set */
  1136. /* ------------------------------------------------------------------ */
  1137. char * decFloatToEngString(const decFloat *df, char *string){
  1138. uInt msd; // coefficient MSD
  1139. Int exp; // exponent top two bits or full
  1140. uInt comb; // combination field
  1141. char *cstart; // coefficient start
  1142. char *c; // output pointer in string
  1143. char *s, *t; // .. (source, target)
  1144. Int pre, e; // work
  1145. const uByte *u; // ..
  1146. uInt uiwork; // for macros [one compiler needs
  1147. // volatile here to avoid bug, but
  1148. // that doubles execution time]
  1149. // Source words; macro handles endianness
  1150. uInt sourhi=DFWORD(df, 0); // word with sign
  1151. #if DECPMAX==16
  1152. uInt sourlo=DFWORD(df, 1);
  1153. #elif DECPMAX==34
  1154. uInt sourmh=DFWORD(df, 1);
  1155. uInt sourml=DFWORD(df, 2);
  1156. uInt sourlo=DFWORD(df, 3);
  1157. #endif
  1158. c=string; // where result will go
  1159. if (((Int)sourhi)<0) *c++='-'; // handle sign
  1160. comb=sourhi>>26; // sign+combination field
  1161. msd=DECCOMBMSD[comb]; // decode the combination field
  1162. exp=DECCOMBEXP[comb]; // ..
  1163. if (EXPISSPECIAL(exp)) { // special
  1164. if (exp==DECFLOAT_Inf) { // infinity
  1165. strcpy(c, "Inf");
  1166. strcpy(c+3, "inity");
  1167. return string; // easy
  1168. }
  1169. if (sourhi&0x02000000) *c++='s'; // sNaN
  1170. strcpy(c, "NaN"); // complete word
  1171. c+=3; // step past
  1172. // quick exit if the payload is zero
  1173. #if DECPMAX==7
  1174. if ((sourhi&0x000fffff)==0) return string;
  1175. #elif DECPMAX==16
  1176. if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;
  1177. #elif DECPMAX==34
  1178. if (sourlo==0 && sourml==0 && sourmh==0
  1179. && (sourhi&0x00003fff)==0) return string;
  1180. #endif
  1181. // otherwise drop through to add integer; set correct exp etc.
  1182. exp=0; msd=0; // setup for following code
  1183. }
  1184. else { // complete exponent; top two bits are in place
  1185. exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias
  1186. }
  1187. /* convert the digits of the significand to characters */
  1188. cstart=c; // save start of coefficient
  1189. if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit
  1190. // Decode the declets. After extracting each declet, it is
  1191. // decoded to a 4-uByte sequence by table lookup; the four uBytes
  1192. // are the three encoded BCD8 digits followed by a 1-byte length
  1193. // (significant digits, except that 000 has length 0). This allows
  1194. // us to left-align the first declet with non-zero content, then
  1195. // the remaining ones are full 3-char length. Fixed-length copies
  1196. // are used because variable-length memcpy causes a subroutine call
  1197. // in at least two compilers. (The copies are length 4 for speed
  1198. // and are safe because the last item in the array is of length
  1199. // three and has the length byte following.)
  1200. #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \
  1201. if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \
  1202. else if (*(u+3)) { \
  1203. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}
  1204. #if DECPMAX==7
  1205. dpd2char(sourhi>>10); // declet 1
  1206. dpd2char(sourhi); // declet 2
  1207. #elif DECPMAX==16
  1208. dpd2char(sourhi>>8); // declet 1
  1209. dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2
  1210. dpd2char(sourlo>>20); // declet 3
  1211. dpd2char(sourlo>>10); // declet 4
  1212. dpd2char(sourlo); // declet 5
  1213. #elif DECPMAX==34
  1214. dpd2char(sourhi>>4); // declet 1
  1215. dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2
  1216. dpd2char(sourmh>>16); // declet 3
  1217. dpd2char(sourmh>>6); // declet 4
  1218. dpd2char((sourmh<<4) | (sourml>>28)); // declet 5
  1219. dpd2char(sourml>>18); // declet 6
  1220. dpd2char(sourml>>8); // declet 7
  1221. dpd2char((sourml<<2) | (sourlo>>30)); // declet 8
  1222. dpd2char(sourlo>>20); // declet 9
  1223. dpd2char(sourlo>>10); // declet 10
  1224. dpd2char(sourlo); // declet 11
  1225. #endif
  1226. if (c==cstart) *c++='0'; // all zeros, empty -- make "0"
  1227. if (exp==0) { // integer or NaN case -- easy
  1228. *c='\0'; // terminate
  1229. return string;
  1230. }
  1231. /* non-0 exponent */
  1232. e=0; // assume no E
  1233. pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]
  1234. // [here, pre-exp is the digits count (==1 for zero)]
  1235. if (exp>0 || pre<-5) { // need exponential form
  1236. e=pre-1; // calculate E value
  1237. pre=1; // assume one digit before '.'
  1238. if (e!=0) { // engineering: may need to adjust
  1239. Int adj; // adjustment
  1240. // The C remainder operator is undefined for negative numbers, so
  1241. // a positive remainder calculation must be used here
  1242. if (e<0) {
  1243. adj=(-e)%3;
  1244. if (adj!=0) adj=3-adj;
  1245. }
  1246. else { // e>0
  1247. adj=e%3;
  1248. }
  1249. e=e-adj;
  1250. // if dealing with zero still produce an exponent which is a
  1251. // multiple of three, as expected, but there will only be the
  1252. // one zero before the E, still. Otherwise note the padding.
  1253. if (!DFISZERO(df)) pre+=adj;
  1254. else { // is zero
  1255. if (adj!=0) { // 0.00Esnn needed
  1256. e=e+3;
  1257. pre=-(2-adj);
  1258. }
  1259. } // zero
  1260. } // engineering adjustment
  1261. } // exponential form
  1262. // printf("e=%ld pre=%ld exp=%ld\n", (LI)e, (LI)pre, (LI)exp);
  1263. /* modify the coefficient, adding 0s, '.', and E+nn as needed */
  1264. if (pre>0) { // ddd.ddd (plain), perhaps with E
  1265. // or dd00 padding for engineering
  1266. char *dotat=cstart+pre;
  1267. if (dotat<c) { // if embedded dot needed...
  1268. // move by fours; there must be space for junk at the end
  1269. // because there is still space for exponent
  1270. s=dotat+ROUNDDOWN4(c-dotat); // source
  1271. t=s+1; // target
  1272. // open the gap [cannot use memcpy]
  1273. for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1274. *dotat='.';
  1275. c++; // length increased by one
  1276. } // need dot?
  1277. else for (; c<dotat; c++) *c='0'; // pad for engineering
  1278. } // pre>0
  1279. else {
  1280. /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (may have
  1281. E, but only for 0.00E+3 kind of case -- with plenty of spare
  1282. space in this case */
  1283. pre=-pre+2; // gap width, including "0."
  1284. t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point
  1285. // backoff if too far to the right
  1286. if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit
  1287. // now shift the entire coefficient to the right, being careful not
  1288. // to access to the left of string [cannot use memcpy]
  1289. for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1290. // for Quads and Singles there may be a character or two left...
  1291. s+=3; // where next would come from
  1292. for(; s>=cstart; s--, t--) *(t+3)=*(s);
  1293. // now have fill 0. through 0.00000; use overlaps to avoid tests
  1294. if (pre>=4) {
  1295. memcpy(cstart+pre-4, "0000", 4);
  1296. memcpy(cstart, "0.00", 4);
  1297. }
  1298. else { // 2 or 3
  1299. *(cstart+pre-1)='0';
  1300. memcpy(cstart, "0.", 2);
  1301. }
  1302. c+=pre; // to end
  1303. }
  1304. // finally add the E-part, if needed; it will never be 0, and has
  1305. // a maximum length of 3 or 4 digits (asserted above)
  1306. if (e!=0) {
  1307. memcpy(c, "E+", 2); // starts with E, assume +
  1308. c++;
  1309. if (e<0) {
  1310. *c='-'; // oops, need '-'
  1311. e=-e; // uInt, please
  1312. }
  1313. c++;
  1314. // Three-character exponents are easy; 4-character a little trickier
  1315. #if DECEMAXD<=3
  1316. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1317. // copy fixed 4 characters [is safe], starting at non-zero
  1318. // and with character mask to convert BCD to char
  1319. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);
  1320. c+=*(u+3); // bump pointer appropriately
  1321. #elif DECEMAXD==4
  1322. if (e<1000) { // 3 (or fewer) digits case
  1323. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1324. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1325. c+=*(u+3); // bump pointer appropriately
  1326. }
  1327. else { // 4-digits
  1328. Int thou=((e>>3)*1049)>>17; // e/1000
  1329. Int rem=e-(1000*thou); // e%1000
  1330. *c++=(char)('0'+(char)thou); // the thousands digit
  1331. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1332. UBFROMUI(c, UBTOUI(u)|CHARMASK);// copy fixed 3+1 characters [is safe]
  1333. c+=3; // bump pointer, always 3 digits
  1334. }
  1335. #endif
  1336. }
  1337. *c='\0'; // terminate
  1338. //printf("res %s\n", string);
  1339. return string;
  1340. } // decFloatToEngString
  1341. /* ------------------------------------------------------------------ */
  1342. /* decFloatToPacked -- convert decFloat to Packed decimal + exponent */
  1343. /* */
  1344. /* df is the source decFloat */
  1345. /* exp will be set to the unbiased exponent, q, or to a special */
  1346. /* value in the form returned by decFloatGetExponent */
  1347. /* packed is where DECPMAX nibbles will be written with the sign as */
  1348. /* final nibble (0x0c for +, 0x0d for -); a NaN has a first nibble */
  1349. /* of zero, and an infinity is all zeros. decDouble and decQuad */
  1350. /* have a additional leading zero nibble, leading to result */
  1351. /* lengths of 4, 9, and 18 bytes. */
  1352. /* returns the sign of the coefficient (DECFLOAT_Sign if negative, */
  1353. /* 0 otherwise) */
  1354. /* */
  1355. /* No error is possible, and no status will be set. */
  1356. /* ------------------------------------------------------------------ */
  1357. Int decFloatToPacked(const decFloat *df, Int *exp, uByte *packed) {
  1358. uByte bcdar[DECPMAX+2]; // work buffer
  1359. uByte *ip=bcdar, *op=packed; // work pointers
  1360. if (DFISINF(df)) {
  1361. memset(bcdar, 0, DECPMAX+2);
  1362. *exp=DECFLOAT_Inf;
  1363. }
  1364. else {
  1365. GETCOEFF(df, bcdar+1); // use macro
  1366. if (DFISNAN(df)) {
  1367. bcdar[1]=0; // MSD needs clearing
  1368. *exp=DFWORD(df, 0)&0x7e000000;
  1369. }
  1370. else { // finite
  1371. *exp=GETEXPUN(df);
  1372. }
  1373. }
  1374. // now pack; coefficient currently at bcdar+1
  1375. #if SINGLE
  1376. ip++; // ignore first byte
  1377. #else
  1378. *ip=0; // need leading zero
  1379. #endif
  1380. // set final byte to Packed BCD sign value
  1381. bcdar[DECPMAX+1]=(DFISSIGNED(df) ? DECPMINUS : DECPPLUS);
  1382. // pack an even number of bytes...
  1383. for (; op<packed+((DECPMAX+2)/2); op++, ip+=2) {
  1384. *op=(uByte)((*ip<<4)+*(ip+1));
  1385. }
  1386. return (bcdar[DECPMAX+1]==DECPMINUS ? DECFLOAT_Sign : 0);
  1387. } // decFloatToPacked
  1388. /* ------------------------------------------------------------------ */
  1389. /* decFloatToString -- conversion to numeric string */
  1390. /* */
  1391. /* df is the decFloat format number to convert */
  1392. /* string is the string where the result will be laid out */
  1393. /* */
  1394. /* string must be at least DECPMAX+9 characters (the worst case is */
  1395. /* "-0.00000nnn...nnn\0", which is as long as the exponent form when */
  1396. /* DECEMAXD<=4); this condition is asserted above */
  1397. /* */
  1398. /* No error is possible, and no status will be set */
  1399. /* ------------------------------------------------------------------ */
  1400. char * decFloatToString(const decFloat *df, char *string){
  1401. uInt msd; // coefficient MSD
  1402. Int exp; // exponent top two bits or full
  1403. uInt comb; // combination field
  1404. char *cstart; // coefficient start
  1405. char *c; // output pointer in string
  1406. char *s, *t; // .. (source, target)
  1407. Int pre, e; // work
  1408. const uByte *u; // ..
  1409. uInt uiwork; // for macros [one compiler needs
  1410. // volatile here to avoid bug, but
  1411. // that doubles execution time]
  1412. // Source words; macro handles endianness
  1413. uInt sourhi=DFWORD(df, 0); // word with sign
  1414. #if DECPMAX==16
  1415. uInt sourlo=DFWORD(df, 1);
  1416. #elif DECPMAX==34
  1417. uInt sourmh=DFWORD(df, 1);
  1418. uInt sourml=DFWORD(df, 2);
  1419. uInt sourlo=DFWORD(df, 3);
  1420. #endif
  1421. c=string; // where result will go
  1422. if (((Int)sourhi)<0) *c++='-'; // handle sign
  1423. comb=sourhi>>26; // sign+combination field
  1424. msd=DECCOMBMSD[comb]; // decode the combination field
  1425. exp=DECCOMBEXP[comb]; // ..
  1426. if (!EXPISSPECIAL(exp)) { // finite
  1427. // complete exponent; top two bits are in place
  1428. exp+=GETECON(df)-DECBIAS; // .. + continuation and unbias
  1429. }
  1430. else { // IS special
  1431. if (exp==DECFLOAT_Inf) { // infinity
  1432. strcpy(c, "Infinity");
  1433. return string; // easy
  1434. }
  1435. if (sourhi&0x02000000) *c++='s'; // sNaN
  1436. strcpy(c, "NaN"); // complete word
  1437. c+=3; // step past
  1438. // quick exit if the payload is zero
  1439. #if DECPMAX==7
  1440. if ((sourhi&0x000fffff)==0) return string;
  1441. #elif DECPMAX==16
  1442. if (sourlo==0 && (sourhi&0x0003ffff)==0) return string;
  1443. #elif DECPMAX==34
  1444. if (sourlo==0 && sourml==0 && sourmh==0
  1445. && (sourhi&0x00003fff)==0) return string;
  1446. #endif
  1447. // otherwise drop through to add integer; set correct exp etc.
  1448. exp=0; msd=0; // setup for following code
  1449. }
  1450. /* convert the digits of the significand to characters */
  1451. cstart=c; // save start of coefficient
  1452. if (msd) *c++=(char)('0'+(char)msd); // non-zero most significant digit
  1453. // Decode the declets. After extracting each declet, it is
  1454. // decoded to a 4-uByte sequence by table lookup; the four uBytes
  1455. // are the three encoded BCD8 digits followed by a 1-byte length
  1456. // (significant digits, except that 000 has length 0). This allows
  1457. // us to left-align the first declet with non-zero content, then
  1458. // the remaining ones are full 3-char length. Fixed-length copies
  1459. // are used because variable-length memcpy causes a subroutine call
  1460. // in at least two compilers. (The copies are length 4 for speed
  1461. // and are safe because the last item in the array is of length
  1462. // three and has the length byte following.)
  1463. #define dpd2char(dpdin) u=&DPD2BCD8[((dpdin)&0x3ff)*4]; \
  1464. if (c!=cstart) {UBFROMUI(c, UBTOUI(u)|CHARMASK); c+=3;} \
  1465. else if (*(u+3)) { \
  1466. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); c+=*(u+3);}
  1467. #if DECPMAX==7
  1468. dpd2char(sourhi>>10); // declet 1
  1469. dpd2char(sourhi); // declet 2
  1470. #elif DECPMAX==16
  1471. dpd2char(sourhi>>8); // declet 1
  1472. dpd2char((sourhi<<2) | (sourlo>>30)); // declet 2
  1473. dpd2char(sourlo>>20); // declet 3
  1474. dpd2char(sourlo>>10); // declet 4
  1475. dpd2char(sourlo); // declet 5
  1476. #elif DECPMAX==34
  1477. dpd2char(sourhi>>4); // declet 1
  1478. dpd2char((sourhi<<6) | (sourmh>>26)); // declet 2
  1479. dpd2char(sourmh>>16); // declet 3
  1480. dpd2char(sourmh>>6); // declet 4
  1481. dpd2char((sourmh<<4) | (sourml>>28)); // declet 5
  1482. dpd2char(sourml>>18); // declet 6
  1483. dpd2char(sourml>>8); // declet 7
  1484. dpd2char((sourml<<2) | (sourlo>>30)); // declet 8
  1485. dpd2char(sourlo>>20); // declet 9
  1486. dpd2char(sourlo>>10); // declet 10
  1487. dpd2char(sourlo); // declet 11
  1488. #endif
  1489. if (c==cstart) *c++='0'; // all zeros, empty -- make "0"
  1490. //[This fast path is valid but adds 3-5 cycles to worst case length]
  1491. //if (exp==0) { // integer or NaN case -- easy
  1492. // *c='\0'; // terminate
  1493. // return string;
  1494. // }
  1495. e=0; // assume no E
  1496. pre=(Int)(c-cstart)+exp; // length+exp [c->LSD+1]
  1497. // [here, pre-exp is the digits count (==1 for zero)]
  1498. if (exp>0 || pre<-5) { // need exponential form
  1499. e=pre-1; // calculate E value
  1500. pre=1; // assume one digit before '.'
  1501. } // exponential form
  1502. /* modify the coefficient, adding 0s, '.', and E+nn as needed */
  1503. if (pre>0) { // ddd.ddd (plain), perhaps with E
  1504. char *dotat=cstart+pre;
  1505. if (dotat<c) { // if embedded dot needed...
  1506. // [memmove is a disaster, here]
  1507. // move by fours; there must be space for junk at the end
  1508. // because exponent is still possible
  1509. s=dotat+ROUNDDOWN4(c-dotat); // source
  1510. t=s+1; // target
  1511. // open the gap [cannot use memcpy]
  1512. for (; s>=dotat; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1513. *dotat='.';
  1514. c++; // length increased by one
  1515. } // need dot?
  1516. // finally add the E-part, if needed; it will never be 0, and has
  1517. // a maximum length of 3 or 4 digits (asserted above)
  1518. if (e!=0) {
  1519. memcpy(c, "E+", 2); // starts with E, assume +
  1520. c++;
  1521. if (e<0) {
  1522. *c='-'; // oops, need '-'
  1523. e=-e; // uInt, please
  1524. }
  1525. c++;
  1526. // Three-character exponents are easy; 4-character a little trickier
  1527. #if DECEMAXD<=3
  1528. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1529. // copy fixed 4 characters [is safe], starting at non-zero
  1530. // and with character mask to convert BCD to char
  1531. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK);
  1532. c+=*(u+3); // bump pointer appropriately
  1533. #elif DECEMAXD==4
  1534. if (e<1000) { // 3 (or fewer) digits case
  1535. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1536. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1537. c+=*(u+3); // bump pointer appropriately
  1538. }
  1539. else { // 4-digits
  1540. Int thou=((e>>3)*1049)>>17; // e/1000
  1541. Int rem=e-(1000*thou); // e%1000
  1542. *c++=(char)('0'+(char)thou); // the thousands digit
  1543. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1544. UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]
  1545. c+=3; // bump pointer, always 3 digits
  1546. }
  1547. #endif
  1548. }
  1549. *c='\0'; // add terminator
  1550. //printf("res %s\n", string);
  1551. return string;
  1552. } // pre>0
  1553. /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
  1554. // Surprisingly, this is close to being the worst-case path, so the
  1555. // shift is done by fours; this is a little tricky because the
  1556. // rightmost character to be written must not be beyond where the
  1557. // rightmost terminator could be -- so backoff to not touch
  1558. // terminator position if need be (this can make exact alignments
  1559. // for full Doubles, but in some cases needs care not to access too
  1560. // far to the left)
  1561. pre=-pre+2; // gap width, including "0."
  1562. t=cstart+ROUNDDOWN4(c-cstart)+pre; // preferred first target point
  1563. // backoff if too far to the right
  1564. if (t>string+DECSTRING-5) t=string+DECSTRING-5; // adjust to fit
  1565. // now shift the entire coefficient to the right, being careful not
  1566. // to access to the left of string [cannot use memcpy]
  1567. for (s=t-pre; s>=string; s-=4, t-=4) UBFROMUI(t, UBTOUI(s));
  1568. // for Quads and Singles there may be a character or two left...
  1569. s+=3; // where next would come from
  1570. for(; s>=cstart; s--, t--) *(t+3)=*(s);
  1571. // now have fill 0. through 0.00000; use overlaps to avoid tests
  1572. if (pre>=4) {
  1573. memcpy(cstart+pre-4, "0000", 4);
  1574. memcpy(cstart, "0.00", 4);
  1575. }
  1576. else { // 2 or 3
  1577. *(cstart+pre-1)='0';
  1578. memcpy(cstart, "0.", 2);
  1579. }
  1580. *(c+pre)='\0'; // terminate
  1581. return string;
  1582. } // decFloatToString
  1583. /* ------------------------------------------------------------------ */
  1584. /* decFloatToWider -- conversion to next-wider format */
  1585. /* */
  1586. /* source is the decFloat format number which gets the result of */
  1587. /* the conversion */
  1588. /* wider is the decFloatWider format number which will be narrowed */
  1589. /* returns wider */
  1590. /* */
  1591. /* Widening is always exact; no status is set (sNaNs are copied and */
  1592. /* do not signal). The result will be canonical if the source is, */
  1593. /* and may or may not be if the source is not. */
  1594. /* ------------------------------------------------------------------ */
  1595. // widening is not possible for decQuad format numbers; simply omit
  1596. #if !QUAD
  1597. decFloatWider * decFloatToWider(const decFloat *source, decFloatWider *wider) {
  1598. uInt msd;
  1599. /* Construct and copy the sign word */
  1600. if (DFISSPECIAL(source)) {
  1601. // copy sign, combination, and first bit of exponent (sNaN selector)
  1602. DFWWORD(wider, 0)=DFWORD(source, 0)&0xfe000000;
  1603. msd=0;
  1604. }
  1605. else { // is finite number
  1606. uInt exp=GETEXPUN(source)+DECWBIAS; // get unbiased exponent and rebias
  1607. uInt code=(exp>>DECWECONL)<<29; // set two bits of exp [msd=0]
  1608. code|=(exp<<(32-6-DECWECONL)) & 0x03ffffff; // add exponent continuation
  1609. code|=DFWORD(source, 0)&0x80000000; // add sign
  1610. DFWWORD(wider, 0)=code; // .. and place top word in wider
  1611. msd=GETMSD(source); // get source coefficient MSD [0-9]
  1612. }
  1613. /* Copy the coefficient and clear any 'unused' words to left */
  1614. #if SINGLE
  1615. DFWWORD(wider, 1)=(DFWORD(source, 0)&0x000fffff)|(msd<<20);
  1616. #elif DOUBLE
  1617. DFWWORD(wider, 2)=(DFWORD(source, 0)&0x0003ffff)|(msd<<18);
  1618. DFWWORD(wider, 3)=DFWORD(source, 1);
  1619. DFWWORD(wider, 1)=0;
  1620. #endif
  1621. return wider;
  1622. } // decFloatToWider
  1623. #endif
  1624. /* ------------------------------------------------------------------ */
  1625. /* decFloatVersion -- return package version string */
  1626. /* */
  1627. /* returns a constant string describing this package */
  1628. /* ------------------------------------------------------------------ */
  1629. const char *decFloatVersion(void) {
  1630. return DECVERSION;
  1631. } // decFloatVersion
  1632. /* ------------------------------------------------------------------ */
  1633. /* decFloatZero -- set to canonical (integer) zero */
  1634. /* */
  1635. /* df is the decFloat format number to integer +0 (q=0, c=+0) */
  1636. /* returns df */
  1637. /* */
  1638. /* No error is possible, and no status can be set. */
  1639. /* ------------------------------------------------------------------ */
  1640. decFloat * decFloatZero(decFloat *df){
  1641. DFWORD(df, 0)=ZEROWORD; // set appropriate top word
  1642. #if DOUBLE || QUAD
  1643. DFWORD(df, 1)=0;
  1644. #if QUAD
  1645. DFWORD(df, 2)=0;
  1646. DFWORD(df, 3)=0;
  1647. #endif
  1648. #endif
  1649. // decFloatShow(df, "zero");
  1650. return df;
  1651. } // decFloatZero
  1652. /* ------------------------------------------------------------------ */
  1653. /* Private generic function (not format-specific) for development use */
  1654. /* ------------------------------------------------------------------ */
  1655. // This is included once only, for all to use
  1656. #if QUAD && (DECCHECK || DECTRACE)
  1657. /* ---------------------------------------------------------------- */
  1658. /* decShowNum -- display bcd8 number in debug form */
  1659. /* */
  1660. /* num is the bcdnum to display */
  1661. /* tag is a string to label the display */
  1662. /* ---------------------------------------------------------------- */
  1663. void decShowNum(const bcdnum *num, const char *tag) {
  1664. const char *csign="+"; // sign character
  1665. uByte *ub; // work
  1666. uInt uiwork; // for macros
  1667. if (num->sign==DECFLOAT_Sign) csign="-";
  1668. printf(">%s> ", tag);
  1669. if (num->exponent==DECFLOAT_Inf) printf("%sInfinity", csign);
  1670. else if (num->exponent==DECFLOAT_qNaN) printf("%sqNaN", csign);
  1671. else if (num->exponent==DECFLOAT_sNaN) printf("%ssNaN", csign);
  1672. else { // finite
  1673. char qbuf[10]; // for right-aligned q
  1674. char *c; // work
  1675. const uByte *u; // ..
  1676. Int e=num->exponent; // .. exponent
  1677. strcpy(qbuf, "q=");
  1678. c=&qbuf[2]; // where exponent will go
  1679. // lay out the exponent
  1680. if (e<0) {
  1681. *c++='-'; // add '-'
  1682. e=-e; // uInt, please
  1683. }
  1684. #if DECEMAXD>4
  1685. #error Exponent form is too long for ShowNum to lay out
  1686. #endif
  1687. if (e==0) *c++='0'; // 0-length case
  1688. else if (e<1000) { // 3 (or fewer) digits case
  1689. u=&BIN2BCD8[e*4]; // -> 3 digits + length byte
  1690. UBFROMUI(c, UBTOUI(u+3-*(u+3))|CHARMASK); // [as above]
  1691. c+=*(u+3); // bump pointer appropriately
  1692. }
  1693. else { // 4-digits
  1694. Int thou=((e>>3)*1049)>>17; // e/1000
  1695. Int rem=e-(1000*thou); // e%1000
  1696. *c++=(char)('0'+(char)thou); // the thousands digit
  1697. u=&BIN2BCD8[rem*4]; // -> 3 digits + length byte
  1698. UBFROMUI(c, UBTOUI(u)|CHARMASK); // copy fixed 3+1 characters [is safe]
  1699. c+=3; // bump pointer, always 3 digits
  1700. }
  1701. *c='\0'; // add terminator
  1702. printf("%7s c=%s", qbuf, csign);
  1703. }
  1704. if (!EXPISSPECIAL(num->exponent) || num->msd!=num->lsd || *num->lsd!=0) {
  1705. for (ub=num->msd; ub<=num->lsd; ub++) { // coefficient...
  1706. printf("%1x", *ub);
  1707. if ((num->lsd-ub)%3==0 && ub!=num->lsd) printf(" "); // 4-space
  1708. }
  1709. }
  1710. printf("\n");
  1711. } // decShowNum
  1712. #endif