decimal64.c 37 KB

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