ItoA实现及测试用例


char * ItoA( int value, char * dest, int r)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
kStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/
ContractedBlock.gif) … {

if (value < 0 && r != 10 )

throw " Exception " ;

int flag = 1 ;

if (value < 0 )
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {

flag = - 1 ;

value = - value;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockEnd.gif) }

char * map = " 0123456789abcdef " ;

char * reDest = dest;

do
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
rs/ContractedSubBlock.gif) … {

  • dest ++ = map[value % r];
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
    lockEnd.gif) } while (value /= r);

    if (flag == - 1 )
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
    lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
    rs/ContractedSubBlock.gif) … {
  • dest ++ = ’ - ’ ;
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
    lockEnd.gif) }
  • dest = ’ /0 ’ ;

    int len = strlen(reDest);

    for ( int i = 0 , j = len - 1 ; i < j; i ++ , j -- )
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
    lockStart.gif) ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicato
    rs/ContractedSubBlock.gif) … {

    swap(reDest[i],reDest[j]);
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubB
    lockEnd.gif) }

    return reDest;
    ![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBloc
    kEnd.gif) }

测试用例:

1.10进制 正数,负数,0

2.16进制 正数

3.0进制 (Crash)

4.进制为负

5.负16进制

6.传入的char数组长度小于生成的数字长度

7.20进制

8.dest为NULL

9.value 为 2^31-1 或 -2^31