免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1802 | 回复: 2
打印 上一主题 下一主题

请教put_dec_trunc函数的算法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-04-27 18:25 |只看该作者 |倒序浏览
./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. }
复制代码

论坛徽章:
0
2 [报告]
发表于 2012-04-27 19:14 |只看该作者
请看你贴的注释~

论坛徽章:
0
3 [报告]
发表于 2012-04-28 16:00 |只看该作者
本帖最后由 du722 于 2012-04-28 16:09 编辑

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

   
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP