深入C++实现函数itoa()的分析

  // TestInheritance.cpp : 定义控制台应用程序的入口点。

  //

  #include "stdafx.h"

  #include

  #include

  #include

  using namespace std;

  int myItoa(int data, char* p, int num)

  {

  if (p == NULL)

  {

  return -1;

  }

  if (data < 0)

  {

  *p++ = '-';

  data = 0 - data;

  }

  int temp = 0;

  int flag = 0; //标志位 0-不存储 1-存储

  if (num == 10)

  {//十进制

  for (int i = 0; i < 10; i++)

  {

  temp = static_cast(data / pow(10.0, 9-i));// pow(i,j),求i的j次方,temp取得当前最高位

  if (temp != 0) //去掉最前面的0

  {

  flag = 1;//将标志位变为1,可以存储

  }

  if (flag != 0)

  {

  *p++ = temp + '0'; //变成字符

  data = data % static_cast(pow(10.0, 9-i));

  }

  }

  }

  else if (num == 2)

  {//二进制

  for (int i = 0; i < 32; i++)

  {

  temp = static_cast(data / pow(2.0, 31-i)); //int型,存储值最大为(2的31次方-1),

  if (temp != 0)

  {

  flag = 1;

  }

  if (flag != 0)

  {

  *p++ = temp + '0';

  data = data % static_cast(pow(2.0, 31 - i));

  }

  }

  }

  else if (num == 16)

  {//十六进制

  for (int i = 0; i < 8; i++)

  {

  temp = static_cast(data / pow(16.0, 7-i));

  if (temp != 0)

  {

  flag = 1;

  }

  if (flag != 0)

  {

  if (temp >= 0 && temp <= 9)

  {

  *p++ = temp + '0';

  }

  else if (temp >= 10 && temp <= 15)

  {

  *p++ = temp - 10 + 'A';

  }

  data = data % static_cast(pow(16.0, 7 - i));

  }

  }

  }

  else if (num == 8)

  {//八进制

  for (int i = 0; i < 16; i++)

  {

  temp = static_cast(data / pow(8.0, 15-i));

  if (temp != 0)

  {

  flag = 1;

  }

  if (flag != 0)

  {

  *p++ = temp + '0';

  data = data % static_cast(pow(8.0, 15-i));

  }

  }

  }

  }

  int _tmain(int argc, _TCHAR* argv[])

  {

  int i = 100;

  char a[32] ={0};

  char b[32] ={0};

  char c[32] ={0};

  char d[32] ={0};

  cout << i << "的八进制表示为: ";

  myItoa(i, a, 8);

  cout << a << endl;

  cout << i << "的十进制表示为: ";

  myItoa(i, b, 10);

  cout << b << endl;

  cout << i << "的二进制表示为: ";

  myItoa(i, c, 2);

  cout << c << endl;

  cout << i << "的十六进制表示为: ";

  myItoa(i, d, 16);

  cout << d << endl;

  return 0;

  }