C语言无符号整型转换字符串,字符串转换无符号整型

char* UInt32toStr(unsigned int n)
{
 
  char buf[10] = "";
  static char str[10]="";
  unsigned int i = 0;
  unsigned int len = 0;
  unsigned int temp = n < 0 ? -n: n;  // temp为n的绝对值
  if(n==0){
    str[0]='0';
    str[1]= 0;
    return &str[0];
  }

  while(temp){
       buf[i++] = (temp % 10) + '0';  //把temp的每一位上的数存入buf
       temp = temp / 10;
      }
 
  len = n < 0 ? ++i: i;  //如果n是负数,则多需要一位来存储负号
  str[i] = 0;            //末尾是结束符0
  while(1)
  {
    i--;
    if (buf[len-i-1] ==0){
        break;
    }
    str[i] = buf[len-i-1];  //把buf数组里的字符拷到字符串
    }
    if (i == 0 ){
           str[i] = '-';          //如果是负数,添加一个负号
       }
    return str;
}

unsigned int StrtoUInt32(const char *str)
{
  unsigned int temp = 0;
  const char *ptr = str;  //ptr保存str字符串开头
 
  if (*str == '-' || *str == '+')  //如果第一个字符是正负号,
    {                      //则移到下一个字符
      str++;
    }
  while(*str != 0){
    if ((*str < '0') || (*str > '9'))  //如果当前字符不是数字
        {                       //则退出循环
          break;
        }
        temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值
        str++;      //移到下一个字符
    }  
  if (*ptr == '-')     //如果字符串是以“-”开头,则转换成其相反数
     {
        temp = -temp;
      }
 
  return temp;
}

猜你喜欢

转载自blog.csdn.net/wuyu92877/article/details/80047610