用过计算机C语言的师兄都应该用过Itoa这个函数,可以很方便的把整数转化为字符串。在单片机开发中,也很需要这个函数,但是单片机开发用的C语言并没有提供Itoa函数,当需要显示整数时很不方便,本人编了一个简易的Itoa函数,可以很方便将整数按指定进制转换为字符串,方便整数显示。供师兄们参考。
- #include<reg52.h>
- //========================================
- unsigned char *Itoa(unsigned int ni,int dd)//ni 要转换的整数;dd进制;
- {char i=0,j=0,temp[16],outstr[16];
- unsigned int n,num=ni;
- while(num>=dd)
- {n=num%dd;
- if(n>9)temp[i]=n+0x37;else temp[i]=n+0x30;
- num=num/dd;
- i++;
- }
- n=num;if(n>9)temp[i]=n+0x37;else temp[i]=n+0x30;
- j=0;
- for(;i>=0;i--){outstr[j]=temp[i];j++;}
- outstr[j]=0;
- return outstr;
- }
- //============================================
- void Uart_init()
- {TMOD=0x22;
- SCON=0x50;
- TH1=0xfd;
- TL1=0xfd;
- EA=1;
- ES=1;
- TR1=1;
- }
- //---------------------------------------------------------------
- void Sentstr(unsigned char *cp)
- {char i=0;
- while(*cp)
- {SBUF=*cp;
- cp++;
- while(!TI);
- TI=0;
- }
- }
- //----------------------------------------------------------------
- void UartPro()interrupt 4{;}
- //=============================================
- main()
- {Uart_init();
- Sentstr("\r253B=");Sentstr(Itoa(253,2));
- Sentstr("\r253O=");Sentstr(Itoa(253,8));
- Sentstr("\r253D=");Sentstr(Itoa(253,10));
- Sentstr("\r253H=");Sentstr(Itoa(253,16));
- while(1);
- }
复制代码 程序运行仿真截图如下:
全部资料51hei下载地址:
Itoa.zip
(64.82 KB, 下载次数: 26)
|