导航

实现itoa()

Posted on 2013-08-10 00:05  codeape  阅读(672)  评论(0编辑  收藏  举报

上代码之前先讲个笑话:曾经有位面试官问:“你实现过 唉踢哦诶(音) 吗”?  我第一个想到的是各种OA系统,心想那玩意不多是Java实现的吗。。。过一会想明白了,瞬间石化。。。

 1 #include <cstdio>
 2 #include <stdint.h>
 3 
 4 int8_t Myitoa(int64_t In_i64SrcNum, uint8_t In_i8Radix, char *In_pcDst)
 5 {
 6     int8_t      i8RetVal    = 0;
 7     //这里强转是为了2、8、16进制显示的时候不需要符号
 8     uint64_t    ui64SrcNum  = (uint64_t)In_i64SrcNum;
 9     char        *pcDst      = In_pcDst;
10     const char  acTable[]   = "0123456789ABCDEF";
11 
12     if (In_i8Radix <= 0 || pcDst == NULL)
13     {
14         i8RetVal = -1;
15         goto fun_ret;
16     }
17 
18     if (ui64SrcNum == 0)
19     {
20         *(pcDst ++) = '0';
21         *pcDst      = 0;
22         goto fun_ret;
23     }
24 
25     if ((int64_t)ui64SrcNum < 0 && In_i8Radix == 10)
26     {
27         ui64SrcNum   = ~ui64SrcNum + 1;
28         *(pcDst ++) = '-';
29     }
30 
31     do //do...while循环的效率较高
32     {
33         *(pcDst ++) = acTable[ui64SrcNum % In_i8Radix];
34         ui64SrcNum   /= In_i8Radix;
35     } while (ui64SrcNum);
36     *pcDst = 0;
37     pcDst --;
38 
39     In_pcDst = *In_pcDst == '-' ? In_pcDst + 1 : In_pcDst;
40     do 
41     {
42         char cTmp   = *In_pcDst;
43         *In_pcDst   = *pcDst;
44         *pcDst      = cTmp;
45         In_pcDst ++;
46         pcDst --;
47     } while (In_pcDst < pcDst);
48 
49 fun_ret:
50     return i8RetVal;
51 }
52 
53 void main()
54 {
55     int64_t i64Test = -1;
56     char    acBinStr[68] = {0};
57     char    acOctStr[28] = {0};
58     char    acDecStr[24] = {0};
59     char    acHexStr[20] = {0};
60     Myitoa(i64Test, 2, acBinStr);
61     Myitoa(i64Test, 8, acOctStr);
62     Myitoa(i64Test, 10, acDecStr);
63     Myitoa(i64Test, 16, acHexStr);
64     printf("%s\n%s\n%s\n%s\n", acBinStr, acOctStr, acDecStr, acHexStr);
65     return;
66 }

趁着找工作这段时间,补补基础,唉,不是科班出身的短板啊。。。

参考:

http://www.cnblogs.com/applebunny/archive/2012/06/21/2557361.html

http://blog.csdn.net/wwwsq/article/details/5137006