decimal32.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* ------------------------------------------------------------------ */
  2. /* Decimal 32-bit format module */
  3. /* ------------------------------------------------------------------ */
  4. /* Copyright (c) IBM Corporation, 2000, 2008. All rights reserved. */
  5. /* */
  6. /* This software is made available under the terms of the */
  7. /* ICU License -- ICU 1.8.1 and later. */
  8. /* */
  9. /* The description and User's Guide ("The decNumber C Library") for */
  10. /* this software is called decNumber.pdf. This document is */
  11. /* available, together with arithmetic and format specifications, */
  12. /* testcases, and Web links, on the General Decimal Arithmetic page. */
  13. /* */
  14. /* Please send comments, suggestions, and corrections to the author: */
  15. /* [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 decimal32 format numbers. */
  20. /* Conversions are supplied to and from decNumber and String. */
  21. /* */
  22. /* This is used when decNumber provides operations, either for all */
  23. /* operations or as a proxy between decNumber and decSingle. */
  24. /* */
  25. /* Error handling is the same as decNumber (qv.). */
  26. /* ------------------------------------------------------------------ */
  27. #include <string.h> // [for memset/memcpy]
  28. #include <stdio.h> // [for printf]
  29. #define DECNUMDIGITS 7 // make decNumbers with space for 7
  30. #include "decNumber.h" // base number library
  31. #include "decNumberLocal.h" // decNumber local types, etc.
  32. #include "decimal32.h" // our primary include
  33. /* Utility tables and routines [in decimal64.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 decDigitsToDPD(const decNumber *, uInt *, Int);
  43. extern void decDigitsFromDPD(decNumber *, const uInt *, Int);
  44. #if DECTRACE || DECCHECK
  45. void decimal32Show(const decimal32 *); // 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. /* ------------------------------------------------------------------ */
  52. /* decimal32FromNumber -- convert decNumber to decimal32 */
  53. /* */
  54. /* ds is the target decimal32 */
  55. /* dn is the source number (assumed valid) */
  56. /* set is the context, used only for reporting errors */
  57. /* */
  58. /* The set argument is used only for status reporting and for the */
  59. /* rounding mode (used if the coefficient is more than DECIMAL32_Pmax */
  60. /* digits or an overflow is detected). If the exponent is out of the */
  61. /* valid range then Overflow or Underflow will be raised. */
  62. /* After Underflow a subnormal result is possible. */
  63. /* */
  64. /* DEC_Clamped is set if the number has to be 'folded down' to fit, */
  65. /* by reducing its exponent and multiplying the coefficient by a */
  66. /* power of ten, or if the exponent on a zero had to be clamped. */
  67. /* ------------------------------------------------------------------ */
  68. decimal32 * decimal32FromNumber(decimal32 *d32, const decNumber *dn,
  69. decContext *set) {
  70. uInt status=0; // status accumulator
  71. Int ae; // adjusted exponent
  72. decNumber dw; // work
  73. decContext dc; // ..
  74. uInt comb, exp; // ..
  75. uInt uiwork; // for macros
  76. uInt targ=0; // target 32-bit
  77. // If the number has too many digits, or the exponent could be
  78. // out of range then reduce the number under the appropriate
  79. // constraints. This could push the number to Infinity or zero,
  80. // so this check and rounding must be done before generating the
  81. // decimal32]
  82. ae=dn->exponent+dn->digits-1; // [0 if special]
  83. if (dn->digits>DECIMAL32_Pmax // too many digits
  84. || ae>DECIMAL32_Emax // likely overflow
  85. || ae<DECIMAL32_Emin) { // likely underflow
  86. decContextDefault(&dc, DEC_INIT_DECIMAL32); // [no traps]
  87. dc.round=set->round; // use supplied rounding
  88. decNumberPlus(&dw, dn, &dc); // (round and check)
  89. // [this changes -0 to 0, so enforce the sign...]
  90. dw.bits|=dn->bits&DECNEG;
  91. status=dc.status; // save status
  92. dn=&dw; // use the work number
  93. } // maybe out of range
  94. if (dn->bits&DECSPECIAL) { // a special value
  95. if (dn->bits&DECINF) targ=DECIMAL_Inf<<24;
  96. else { // sNaN or qNaN
  97. if ((*dn->lsu!=0 || dn->digits>1) // non-zero coefficient
  98. && (dn->digits<DECIMAL32_Pmax)) { // coefficient fits
  99. decDigitsToDPD(dn, &targ, 0);
  100. }
  101. if (dn->bits&DECNAN) targ|=DECIMAL_NaN<<24;
  102. else targ|=DECIMAL_sNaN<<24;
  103. } // a NaN
  104. } // special
  105. else { // is finite
  106. if (decNumberIsZero(dn)) { // is a zero
  107. // set and clamp exponent
  108. if (dn->exponent<-DECIMAL32_Bias) {
  109. exp=0; // low clamp
  110. status|=DEC_Clamped;
  111. }
  112. else {
  113. exp=dn->exponent+DECIMAL32_Bias; // bias exponent
  114. if (exp>DECIMAL32_Ehigh) { // top clamp
  115. exp=DECIMAL32_Ehigh;
  116. status|=DEC_Clamped;
  117. }
  118. }
  119. comb=(exp>>3) & 0x18; // msd=0, exp top 2 bits ..
  120. }
  121. else { // non-zero finite number
  122. uInt msd; // work
  123. Int pad=0; // coefficient pad digits
  124. // the dn is known to fit, but it may need to be padded
  125. exp=(uInt)(dn->exponent+DECIMAL32_Bias); // bias exponent
  126. if (exp>DECIMAL32_Ehigh) { // fold-down case
  127. pad=exp-DECIMAL32_Ehigh;
  128. exp=DECIMAL32_Ehigh; // [to maximum]
  129. status|=DEC_Clamped;
  130. }
  131. // fastpath common case
  132. if (DECDPUN==3 && pad==0) {
  133. targ=BIN2DPD[dn->lsu[0]];
  134. if (dn->digits>3) targ|=(uInt)(BIN2DPD[dn->lsu[1]])<<10;
  135. msd=(dn->digits==7 ? dn->lsu[2] : 0);
  136. }
  137. else { // general case
  138. decDigitsToDPD(dn, &targ, pad);
  139. // save and clear the top digit
  140. msd=targ>>20;
  141. targ&=0x000fffff;
  142. }
  143. // create the combination field
  144. if (msd>=8) comb=0x18 | ((exp>>5) & 0x06) | (msd & 0x01);
  145. else comb=((exp>>3) & 0x18) | msd;
  146. }
  147. targ|=comb<<26; // add combination field ..
  148. targ|=(exp&0x3f)<<20; // .. and exponent continuation
  149. } // finite
  150. if (dn->bits&DECNEG) targ|=0x80000000; // add sign bit
  151. // now write to storage; this is endian
  152. UBFROMUI(d32->bytes, targ); // directly store the int
  153. if (status!=0) decContextSetStatus(set, status); // pass on status
  154. // decimal32Show(d32);
  155. return d32;
  156. } // decimal32FromNumber
  157. /* ------------------------------------------------------------------ */
  158. /* decimal32ToNumber -- convert decimal32 to decNumber */
  159. /* d32 is the source decimal32 */
  160. /* dn is the target number, with appropriate space */
  161. /* No error is possible. */
  162. /* ------------------------------------------------------------------ */
  163. decNumber * decimal32ToNumber(const decimal32 *d32, decNumber *dn) {
  164. uInt msd; // coefficient MSD
  165. uInt exp; // exponent top two bits
  166. uInt comb; // combination field
  167. uInt sour; // source 32-bit
  168. uInt uiwork; // for macros
  169. // load source from storage; this is endian
  170. sour=UBTOUI(d32->bytes); // directly load the int
  171. comb=(sour>>26)&0x1f; // combination field
  172. decNumberZero(dn); // clean number
  173. if (sour&0x80000000) dn->bits=DECNEG; // set sign if negative
  174. msd=COMBMSD[comb]; // decode the combination field
  175. exp=COMBEXP[comb]; // ..
  176. if (exp==3) { // is a special
  177. if (msd==0) {
  178. dn->bits|=DECINF;
  179. return dn; // no coefficient needed
  180. }
  181. else if (sour&0x02000000) dn->bits|=DECSNAN;
  182. else dn->bits|=DECNAN;
  183. msd=0; // no top digit
  184. }
  185. else { // is a finite number
  186. dn->exponent=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased
  187. }
  188. // get the coefficient
  189. sour&=0x000fffff; // clean coefficient continuation
  190. if (msd) { // non-zero msd
  191. sour|=msd<<20; // prefix to coefficient
  192. decDigitsFromDPD(dn, &sour, 3); // process 3 declets
  193. return dn;
  194. }
  195. // msd=0
  196. if (!sour) return dn; // easy: coefficient is 0
  197. if (sour&0x000ffc00) // need 2 declets?
  198. decDigitsFromDPD(dn, &sour, 2); // process 2 declets
  199. else
  200. decDigitsFromDPD(dn, &sour, 1); // process 1 declet
  201. return dn;
  202. } // decimal32ToNumber
  203. /* ------------------------------------------------------------------ */
  204. /* to-scientific-string -- conversion to numeric string */
  205. /* to-engineering-string -- conversion to numeric string */
  206. /* */
  207. /* decimal32ToString(d32, string); */
  208. /* decimal32ToEngString(d32, string); */
  209. /* */
  210. /* d32 is the decimal32 format number to convert */
  211. /* string is the string where the result will be laid out */
  212. /* */
  213. /* string must be at least 24 characters */
  214. /* */
  215. /* No error is possible, and no status can be set. */
  216. /* ------------------------------------------------------------------ */
  217. char * decimal32ToEngString(const decimal32 *d32, char *string){
  218. decNumber dn; // work
  219. decimal32ToNumber(d32, &dn);
  220. decNumberToEngString(&dn, string);
  221. return string;
  222. } // decimal32ToEngString
  223. char * decimal32ToString(const decimal32 *d32, char *string){
  224. uInt msd; // coefficient MSD
  225. Int exp; // exponent top two bits or full
  226. uInt comb; // combination field
  227. char *cstart; // coefficient start
  228. char *c; // output pointer in string
  229. const uByte *u; // work
  230. char *s, *t; // .. (source, target)
  231. Int dpd; // ..
  232. Int pre, e; // ..
  233. uInt uiwork; // for macros
  234. uInt sour; // source 32-bit
  235. // load source from storage; this is endian
  236. sour=UBTOUI(d32->bytes); // directly load the int
  237. c=string; // where result will go
  238. if (((Int)sour)<0) *c++='-'; // handle sign
  239. comb=(sour>>26)&0x1f; // combination field
  240. msd=COMBMSD[comb]; // decode the combination field
  241. exp=COMBEXP[comb]; // ..
  242. if (exp==3) {
  243. if (msd==0) { // infinity
  244. strcpy(c, "Inf");
  245. strcpy(c+3, "inity");
  246. return string; // easy
  247. }
  248. if (sour&0x02000000) *c++='s'; // sNaN
  249. strcpy(c, "NaN"); // complete word
  250. c+=3; // step past
  251. if ((sour&0x000fffff)==0) return string; // zero payload
  252. // otherwise drop through to add integer; set correct exp
  253. exp=0; msd=0; // setup for following code
  254. }
  255. else exp=(exp<<6)+((sour>>20)&0x3f)-DECIMAL32_Bias; // unbiased
  256. // convert 7 digits of significand to characters
  257. cstart=c; // save start of coefficient
  258. if (msd) *c++='0'+(char)msd; // non-zero most significant digit
  259. // Now decode the declets. After extracting each one, it is
  260. // decoded to binary and then to a 4-char sequence by table lookup;
  261. // the 4-chars are a 1-char length (significant digits, except 000
  262. // has length 0). This allows us to left-align the first declet
  263. // with non-zero content, then remaining ones are full 3-char
  264. // length. We use fixed-length memcpys because variable-length
  265. // causes a subroutine call in GCC. (These are length 4 for speed
  266. // and are safe because the array has an extra terminator byte.)
  267. #define dpd2char u=&BIN2CHAR[DPD2BIN[dpd]*4]; \
  268. if (c!=cstart) {memcpy(c, u+1, 4); c+=3;} \
  269. else if (*u) {memcpy(c, u+4-*u, 4); c+=*u;}
  270. dpd=(sour>>10)&0x3ff; // declet 1
  271. dpd2char;
  272. dpd=(sour)&0x3ff; // declet 2
  273. dpd2char;
  274. if (c==cstart) *c++='0'; // all zeros -- make 0
  275. if (exp==0) { // integer or NaN case -- easy
  276. *c='\0'; // terminate
  277. return string;
  278. }
  279. /* non-0 exponent */
  280. e=0; // assume no E
  281. pre=c-cstart+exp;
  282. // [here, pre-exp is the digits count (==1 for zero)]
  283. if (exp>0 || pre<-5) { // need exponential form
  284. e=pre-1; // calculate E value
  285. pre=1; // assume one digit before '.'
  286. } // exponential form
  287. /* modify the coefficient, adding 0s, '.', and E+nn as needed */
  288. s=c-1; // source (LSD)
  289. if (pre>0) { // ddd.ddd (plain), perhaps with E
  290. char *dotat=cstart+pre;
  291. if (dotat<c) { // if embedded dot needed...
  292. t=c; // target
  293. for (; s>=dotat; s--, t--) *t=*s; // open the gap; leave t at gap
  294. *t='.'; // insert the dot
  295. c++; // length increased by one
  296. }
  297. // finally add the E-part, if needed; it will never be 0, and has
  298. // a maximum length of 3 digits (E-101 case)
  299. if (e!=0) {
  300. *c++='E'; // starts with E
  301. *c++='+'; // assume positive
  302. if (e<0) {
  303. *(c-1)='-'; // oops, need '-'
  304. e=-e; // uInt, please
  305. }
  306. u=&BIN2CHAR[e*4]; // -> length byte
  307. memcpy(c, u+4-*u, 4); // copy fixed 4 characters [is safe]
  308. c+=*u; // bump pointer appropriately
  309. }
  310. *c='\0'; // add terminator
  311. //printf("res %s\n", string);
  312. return string;
  313. } // pre>0
  314. /* -5<=pre<=0: here for plain 0.ddd or 0.000ddd forms (can never have E) */
  315. t=c+1-pre;
  316. *(t+1)='\0'; // can add terminator now
  317. for (; s>=cstart; s--, t--) *t=*s; // shift whole coefficient right
  318. c=cstart;
  319. *c++='0'; // always starts with 0.
  320. *c++='.';
  321. for (; pre<0; pre++) *c++='0'; // add any 0's after '.'
  322. //printf("res %s\n", string);
  323. return string;
  324. } // decimal32ToString
  325. /* ------------------------------------------------------------------ */
  326. /* to-number -- conversion from numeric string */
  327. /* */
  328. /* decimal32FromString(result, string, set); */
  329. /* */
  330. /* result is the decimal32 format number which gets the result of */
  331. /* the conversion */
  332. /* *string is the character string which should contain a valid */
  333. /* number (which may be a special value) */
  334. /* set is the context */
  335. /* */
  336. /* The context is supplied to this routine is used for error handling */
  337. /* (setting of status and traps) and for the rounding mode, only. */
  338. /* If an error occurs, the result will be a valid decimal32 NaN. */
  339. /* ------------------------------------------------------------------ */
  340. decimal32 * decimal32FromString(decimal32 *result, const char *string,
  341. decContext *set) {
  342. decContext dc; // work
  343. decNumber dn; // ..
  344. decContextDefault(&dc, DEC_INIT_DECIMAL32); // no traps, please
  345. dc.round=set->round; // use supplied rounding
  346. decNumberFromString(&dn, string, &dc); // will round if needed
  347. decimal32FromNumber(result, &dn, &dc);
  348. if (dc.status!=0) { // something happened
  349. decContextSetStatus(set, dc.status); // .. pass it on
  350. }
  351. return result;
  352. } // decimal32FromString
  353. /* ------------------------------------------------------------------ */
  354. /* decimal32IsCanonical -- test whether encoding is canonical */
  355. /* d32 is the source decimal32 */
  356. /* returns 1 if the encoding of d32 is canonical, 0 otherwise */
  357. /* No error is possible. */
  358. /* ------------------------------------------------------------------ */
  359. uInt decimal32IsCanonical(const decimal32 *d32) {
  360. decNumber dn; // work
  361. decimal32 canon; // ..
  362. decContext dc; // ..
  363. decContextDefault(&dc, DEC_INIT_DECIMAL32);
  364. decimal32ToNumber(d32, &dn);
  365. decimal32FromNumber(&canon, &dn, &dc);// canon will now be canonical
  366. return memcmp(d32, &canon, DECIMAL32_Bytes)==0;
  367. } // decimal32IsCanonical
  368. /* ------------------------------------------------------------------ */
  369. /* decimal32Canonical -- copy an encoding, ensuring it is canonical */
  370. /* d32 is the source decimal32 */
  371. /* result is the target (may be the same decimal32) */
  372. /* returns result */
  373. /* No error is possible. */
  374. /* ------------------------------------------------------------------ */
  375. decimal32 * decimal32Canonical(decimal32 *result, const decimal32 *d32) {
  376. decNumber dn; // work
  377. decContext dc; // ..
  378. decContextDefault(&dc, DEC_INIT_DECIMAL32);
  379. decimal32ToNumber(d32, &dn);
  380. decimal32FromNumber(result, &dn, &dc);// result will now be canonical
  381. return result;
  382. } // decimal32Canonical
  383. #if DECTRACE || DECCHECK
  384. /* Macros for accessing decimal32 fields. These assume the argument
  385. is a reference (pointer) to the decimal32 structure, and the
  386. decimal32 is in network byte order (big-endian) */
  387. // Get sign
  388. #define decimal32Sign(d) ((unsigned)(d)->bytes[0]>>7)
  389. // Get combination field
  390. #define decimal32Comb(d) (((d)->bytes[0] & 0x7c)>>2)
  391. // Get exponent continuation [does not remove bias]
  392. #define decimal32ExpCon(d) ((((d)->bytes[0] & 0x03)<<4) \
  393. | ((unsigned)(d)->bytes[1]>>4))
  394. // Set sign [this assumes sign previously 0]
  395. #define decimal32SetSign(d, b) { \
  396. (d)->bytes[0]|=((unsigned)(b)<<7);}
  397. // Set exponent continuation [does not apply bias]
  398. // This assumes range has been checked and exponent previously 0;
  399. // type of exponent must be unsigned
  400. #define decimal32SetExpCon(d, e) { \
  401. (d)->bytes[0]|=(uByte)((e)>>4); \
  402. (d)->bytes[1]|=(uByte)(((e)&0x0F)<<4);}
  403. /* ------------------------------------------------------------------ */
  404. /* decimal32Show -- display a decimal32 in hexadecimal [debug aid] */
  405. /* d32 -- the number to show */
  406. /* ------------------------------------------------------------------ */
  407. // Also shows sign/cob/expconfields extracted - valid bigendian only
  408. void decimal32Show(const decimal32 *d32) {
  409. char buf[DECIMAL32_Bytes*2+1];
  410. Int i, j=0;
  411. if (DECLITEND) {
  412. for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
  413. sprintf(&buf[j], "%02x", d32->bytes[3-i]);
  414. }
  415. printf(" D32> %s [S:%d Cb:%02x Ec:%02x] LittleEndian\n", buf,
  416. d32->bytes[3]>>7, (d32->bytes[3]>>2)&0x1f,
  417. ((d32->bytes[3]&0x3)<<4)| (d32->bytes[2]>>4));
  418. }
  419. else {
  420. for (i=0; i<DECIMAL32_Bytes; i++, j+=2) {
  421. sprintf(&buf[j], "%02x", d32->bytes[i]);
  422. }
  423. printf(" D32> %s [S:%d Cb:%02x Ec:%02x] BigEndian\n", buf,
  424. decimal32Sign(d32), decimal32Comb(d32), decimal32ExpCon(d32));
  425. }
  426. } // decimal32Show
  427. #endif