Chinaunix

标题: 请教put_dec_trunc函数的算法 [打印本页]

作者: du722    时间: 2012-04-27 18:25
标题: 请教put_dec_trunc函数的算法
./lib/vsprintf.c文件中有个将10进制转换为字符串的函数,对其算法不明,请大侠指点,不胜感激。
源码如下:
  1. /* Decimal conversion is by far the most typical, and is used
  2. * for /proc and /sys data. This directly impacts e.g. top performance
  3. * with many processes running. We optimize it for speed
  4. * using code from
  5. * http://www.cs.uiowa.edu/~jones/bcd/decimal.html
  6. * (with permission from the author, Douglas W. Jones). */

  7. /* Formats correctly any integer in [0,99999].
  8. * Outputs from one to five digits depending on input.
  9. * On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
  10. static char* put_dec_trunc(char *buf, unsigned q)
  11. {
  12.         unsigned d3, d2, d1, d0;
  13.         d1 = (q>>4) & 0xf;
  14.         d2 = (q>>8) & 0xf;
  15.         d3 = (q>>12);

  16.         d0 = 6*(d3 + d2 + d1) + (q & 0xf);
  17.         q = (d0 * 0xcd) >> 11;
  18.         d0 = d0 - 10*q;
  19.         *buf++ = d0 + '0'; /* least significant digit */
  20.         d1 = q + 9*d3 + 5*d2 + d1;
  21.         if (d1 != 0) {
  22.                 q = (d1 * 0xcd) >> 11;
  23.                 d1 = d1 - 10*q;
  24.                 *buf++ = d1 + '0'; /* next digit */

  25.                 d2 = q + 2*d2;
  26.                 if ((d2 != 0) || (d3 != 0)) {
  27.                         q = (d2 * 0xd) >> 7;
  28.                         d2 = d2 - 10*q;
  29.                         *buf++ = d2 + '0'; /* next digit */

  30.                         d3 = q + 4*d3;
  31.                         if (d3 != 0) {
  32.                                 q = (d3 * 0xcd) >> 11;
  33.                                 d3 = d3 - 10*q;
  34.                                 *buf++ = d3 + '0';  /* next digit */
  35.                                 if (q != 0)
  36.                                         *buf++ = q + '0';  /* most sign. digit */
  37.                         }
  38.                 }
  39.         }
  40.         return buf;
  41. }
复制代码

作者: wangjianchangdx    时间: 2012-04-27 19:14
请看你贴的注释~
作者: du722    时间: 2012-04-28 16:00
本帖最后由 du722 于 2012-04-28 16:09 编辑

回复 2# wangjianchangdx
谢谢指点,是我自己看代码不仔细,根据http://www.cs.uiowa.edu/~jones/bcd/decimal.html中的讲解,初步理解了算法。

   




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2