自己练练了手,写了两个程序:
第一个:十进制的数字转化为16进制
- intmain(intargc,_TCHAR*argv[])
- {
- inta=100000000,i=0,b;
- intc[8]={0};
- printf("%10.4x",a);
- while(a){
- b=a-(a>>4<<4);
- c[i]=b;
- i++;
- a=a>>4;
- }
- i=i-1;
- printf("Thenumberofhexis:");
- for(intindex=i;index>=0;index--)
- printf("%x",c[index]);
- printf("");
- return0;
- }
第二个,将ascII字符转化为十进制数字, 不是数字的转化!
- #include<iostream>
- #include<stdio.h>
- usingnamespacestd;
- intmain(){
- char*str="asd";
- constintN=strlen(str);
- int*array=newint[N-1];
- inti=0;
- while(*str!='\0'){
- array[i]=(int)(*str);//直接转化存储即可
- cout<<array[i]<<endl;
- i++;
- str++;
- }
- }
3、数字的转化为字符串,字符串转为数字:
- #include<stdio.h>
- #include<stdlib.h>
- char*i_to_a(intvalue){
- chartemp[30];
- char*result;
- inti=0,j=0;
- while(value!=0){
- temp[i]=value%10+48;
- value/=10;
- i++;
- }
- result=(char*)malloc(sizeof(char)*(i+1));
- for(j=0;j<i;j++){
- result[j]=temp[i-1-j];
- }
- result[j]='\0';
- returnresult;
- }
- boola_to_i(char*a,int*num){
- char*p=a;
- inti=0;
- *num=0;
- //checkthestring
- if((*p=='+')||(*p=='-'))
- i=1;
- while(*(p+i)!='\0'){
- if(*(p+i)>='0'&&*(p+i)<='9'){
- i++;
- }
- else{
- printf("Illegall!\n");
- return1;
- }
- }
- if(i==1){
- printf("Illegall!\n");
- return1;
- }
- //startconverting,herethestringisinarightformulation
- while(*p!='\0'){
- if((*p=='+')||(*p=='-')){
- p++;
- }
- else{
- *num=*num*10+*p-'0';
- p++;
- }
- }
- if(*a=='-'){
- *num=-(*num);
- }
- else{
- }
- return0;
- }
- intmain(){
- inti=6553567;
- char*p=i_to_a(i);
- printf("%s\n",p);
- free(p);
- intnum=0;
- if(!a_to_i("0000",&num))
- printf("num=%d\n",num);
- return0;
- }
4 数字的转化为字符串,字符串转为数字(2):
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
- voidmyitoa_first(longlonga,char*p){
- if(a==0)
- {
- *p='\0';
- }
- else{
- myitoa_first(a/10,p+1);
- *p=a%10+'0';
- }
- }
- voidmyitoa_second(char*p){
- char*p1=p;
- char*p2=p+strlen(p)-1;
- inta;
- while(p1<p2)
- {
- a=*p2;
- *p2=*p1;
- *p1=a;
- p1++;
- p2--;
- }
- }
- voidmyitoa(longlonga,char*p){
- myitoa_first(a,p);
- myitoa_second(p);
- }
- intmyatoi(char*pp){
- char*p=pp;
- intsum=0;
- boolflag=0;
- if(*p=='+')
- {
- flag=0;
- p++;
- }
- elseif(*p=='-')
- {
- flag=1;
- p++;
- }
- while(*p!='\0')
- {
- if(*p>='0'&&*p<='9')
- {
- sum=sum*10+*p-'0';
- p++;
- }
- else
- break;
- }
- if(flag)
- {
- sum*=-1;
- }
- returnsum;
- }
- intmain(){
- char*p=(char*)malloc(32*sizeof(char));
- longlonga=12345;
- myitoa(a,p);
- printf(p);
- puts("");
- char*pp="-1234567s89";
- intaa=myatoi(pp);
- printf("a=%d\n",aa);
- }
数字转换技巧
本文提供了几个实用的数字转换程序,包括十进制到十六进制的转换、ASCII字符到十进制数字的转换以及数字和字符串之间的相互转换。这些程序使用C/C++语言实现,为开发者提供了基本的数据类型转换思路。
496

被折叠的 条评论
为什么被折叠?



