Source code implementation of ITOA

Source: Internet
Author: User

由于通过socket传递数据的时候,仅仅能够通过字符串类型,可是,当我们要传递的数据是整型的是,应该怎么办呢?本来我想着使用for循环,可是,总感觉太麻烦了,后来别人告诉我能够使用itoa,以下是itoa的原型:

char *itoa(int value, char *string, int radix);

举比例如以下:

#include <iostream>#include <cstring>using namespace std;int main(){char arr[10];int a=123456;itoa(a,arr,10);cout<<arr<<endl;cout<<strlen(arr)<<endl;return 0;}


可是,正在高兴的时候,才发如今Unix下没有itoa函数,上网上一搜,才发现itoa不是标准的C语言函数,以下是百度百科中的解释:

itoa是广泛应用的非标准C语言扩展函数。因为它不是标准C语言函数,所以不能在全部的编译器中使用。可是,大多数的编译器(如Windows上的)通常在<stdlib.h>头文件里包括这个函数。在<stdlib.h>中与之有相反功能的函数是atoi。

 

那应该怎么办呢?

后来同事告诉我,能够使用万能的sprintf啊,我恍然大悟,以下举一个小样例:

#include <iostream>using namespace std;int main(){char arr[10];int a=123;sprintf(arr,"%d",a);cout<<arr<<endl;}

 

我当时挺想知道itoa内部究竟是怎么实现的,在网上搜了一个样例,感觉写的的挺不错的,我把这个实现itoa的源代码的文件改动了一下,能够执行了,以下是源代码:

#include <stdlib.h> #include <stdio.h> char *myitoa(int num,char *str,int radix);int main() { int number = -123456; char string[25]; myitoa(number, string, 16); printf("integer = %d string = %s\n", number, string); return 0; } /* 实现itoa函数的源码 */ char *myitoa(int num,char *str,int radix) {  /* 索引表 */ char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; unsigned unum; /* 中间变量 */ int i=0,j,k; /* 确定unum的值 */ if(radix==10&&num<0) /* 十进制负数 */ { unum=(unsigned)-num; str[i++]=‘-‘; } else unum=(unsigned)num; /* 其它情况 */ /* 逆序 */ do  { str[i++]=index[unum%(unsigned)radix]; unum/=radix; }while(unum); str[i]=‘\0‘; /* 转换 */ if(str[0]==‘-‘) k=1; /* 十进制负数 */ else k=0; /* 将原来的“/2”改为“/2.0”,保证当num在16~255之间,radix等于16时,也能得到正确结果 */ char temp; for(j=k;j<=(i-k-1)/2.0;j++) { temp=str[j]; str[j]=str[i-j-1]; str[i-j-1]=temp; } return str; } 


扩展阅读: http://baike.baidu.com/view/982195.htm

 

我在网上搜memcpy的时候,网上有一句话“memcpy能够复制随意内容,比如字符数组、整型、结构体、类等”,所以我想着使用memcpy应该也能够实现上面这个问题,希望看过这篇文章的不吝赐教一下,谢谢!

itoa的源代码实现

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.