Chinaunix
标题:
请教put_dec_trunc函数的算法
[打印本页]
作者:
du722
时间:
2012-04-27 18:25
标题:
请教put_dec_trunc函数的算法
./lib/vsprintf.c文件中有个将10进制转换为字符串的函数,对其算法不明,请大侠指点,不胜感激。
源码如下:
/* Decimal conversion is by far the most typical, and is used
* for /proc and /sys data. This directly impacts e.g. top performance
* with many processes running. We optimize it for speed
* using code from
* http://www.cs.uiowa.edu/~jones/bcd/decimal.html
* (with permission from the author, Douglas W. Jones). */
/* Formats correctly any integer in [0,99999].
* Outputs from one to five digits depending on input.
* On i386 gcc 4.1.2 -O2: ~250 bytes of code. */
static char* put_dec_trunc(char *buf, unsigned q)
{
unsigned d3, d2, d1, d0;
d1 = (q>>4) & 0xf;
d2 = (q>>8) & 0xf;
d3 = (q>>12);
d0 = 6*(d3 + d2 + d1) + (q & 0xf);
q = (d0 * 0xcd) >> 11;
d0 = d0 - 10*q;
*buf++ = d0 + '0'; /* least significant digit */
d1 = q + 9*d3 + 5*d2 + d1;
if (d1 != 0) {
q = (d1 * 0xcd) >> 11;
d1 = d1 - 10*q;
*buf++ = d1 + '0'; /* next digit */
d2 = q + 2*d2;
if ((d2 != 0) || (d3 != 0)) {
q = (d2 * 0xd) >> 7;
d2 = d2 - 10*q;
*buf++ = d2 + '0'; /* next digit */
d3 = q + 4*d3;
if (d3 != 0) {
q = (d3 * 0xcd) >> 11;
d3 = d3 - 10*q;
*buf++ = d3 + '0'; /* next digit */
if (q != 0)
*buf++ = q + '0'; /* most sign. digit */
}
}
}
return buf;
}
复制代码
作者:
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