日期:2014-05-16  浏览次数:20647 次

Linux C 内核代码中 整型转化为字符串 的 问题、。
C/C++ code
#include <config.h>

#include "inttostr.h"

/* Convert I to a printable string in BUF, which must be at least
   INT_BUFSIZE_BOUND (INTTYPE) bytes long. 
    Return the address of theprintable string, which need not start at BUF.  
    buf的长度必须大于等于INT_BUFSIZE_BOUND (INTTYPE) bytes long*/

char *
inttostr (inttype i, char *buf)
{
  char *p = buf + INT_STRLEN_BOUND (inttype);//p指向内存的尾端;
  *p = 0;//末端置0;

  if (i < 0)
    {
      do
    *--p = '0' - i % 10;
      while ((i /= 10) != 0);

      *--p = '-';
    }
  else
    {
      do
    *--p = '0' + i % 10;
      while ((i /= 10) != 0);
    }

  return p;
}

中间 这句 *--p = '0' - i % 10; 是什么意思:

还有下面 这句 *--p = '0' + i % 10; ??

------解决方案--------------------
先看i为正数的情况:
*--p = '0' + i % 10;
i%10得到最后的一位,加上'0'是将整数x转换为字符'x'

为负数的时候也是一样,只是余数为负数,故中间为减号
------解决方案--------------------
i<0
负数
--得正 , '0'+字符串最后一个数
循环
完了在加个-号

这样吧?