挖出 itoa

来源:互联网 发布:iphone看书软件哪个好 编辑:程序博客网 时间:2024/04/28 02:48

下面是 itoa 的实现(出自 solaris),虽然函数小,可他的实现方法很独特,里面有些知识点值得学习。这个问题是我正在找工作等待面试的同志问我的,其实我也不会。后来是在网上找到的。这里只想把它弄明白,多个学习的机会。

// implementation in solaris
char* itoa(long n/* abs k16 */, int base)
{
register char *p;
register int minus;
static char buf[36];

p = &buf[36];
*--p = '/0';
if (n < 0)
{
minus = 1;
n = -n;
}
else
minus = 0;

if (n == 0)
*--p = '0';
else
while (n > 0)
{
*--p = "0123456789abcdef"[n % base];
n /= base;
}
if (minus)
*--p = '-';
return p;
}


我在 codeproject 上发的贴子
http://www.codeproject.com/script/comments/forums.asp?msg=1377551&forumid=1647#xx1377551xx

原创粉丝点击