int 与 char* 互转

int 与 char* 互转


#include "stdafx.h"
#include "string.h"

int ConvertCharToInt(char* p)
{
  if (p == NULL)
    return -1;

  int n = 0;

  while(*p > '0' && *p < '9')
  {
    n *=10;
    n += *p - '0';
    p++;
  }

  return n;

}

bool ConvertIntToChar(int n, char* p)
{
  if (p == NULL)
    return false;

  int i = 0;
  char buf[256] = "";
  while(n)
  {
    buf[i++] = n % 10 + '0';

    n = (int) n / 10;
  }

  buf[i] = '\0';

  // reverse and copy
  int len = strlen(buf);
  int m = 0;
  for (int n = len-1; n > -1; n --, m++)
  {
    p[m] = buf[n];
  }

  p[m] = '\0';

  // copy
  //_strrev(buf);
  //strcpy(p,buf);


  return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
  char* p =  "1314";
  int n = ConvertCharToInt(p);

  char buf[256] = "";
  bool b = ConvertIntToChar(1314, buf);

  return 0;
}



你可能感兴趣的:(int 与 char* 互转)