atoi和itoa的实现

3 篇文章 0 订阅
#include <stdio.h>



int str2num(const char *s){

    

    int i;

    char c;    

    for (i = 0; '0' <= (c = *s) && c <= '9'; ++s)

        i = i*10 + c - '0';

    return i;

}



double str2double(const char *s){

	

	int iValue = 0;

	double dValue = 0.0;

	

	//bool bDot = false;

	char c;

	for ( ; '0' <= (c = *s) && c <= '9' ; ++s){

	    iValue = iValue * 10 + c - '0';

    }

    

    if( c && '.' == c){

    	int base = 1;

    	const char *tmp = ++ s;

    	while( *tmp++ != '/0' ) base = base * 10;

  

    	for ( ; '0' <= (c = *s) && c <= '9' ; ++s){

	        dValue = dValue * 10 + c - '0';

        }

        

        dValue = dValue / base;

        

    }

    

    return iValue + dValue;

	

}



char * int2str(long n, int base, char *buf, int length)

{

	char *p = buf ;

	int minus;

	p = &buf[length];

	*--p = '/0';

	if (n < 0) {

		minus = 1;

		n = -n;

	}

	else

		minus = 0;

	if (n == 0)

		*--p = '0';

	else

		while (n > 0) {

			*--p = "0123456789abcdef"[n % base];

			n /= base;

		}

	if (minus)

		*--p = '-';

	return p;

}



int main(){

    char *str = "75979";

    char *dStr = "75979.534";

    printf("%s, %d/n", str, str2num( str ) );

    printf("%s, %.3f/n", dStr, str2double( dStr ) );

    

    int iInt = -12345;

    char cStr[10];

    printf("%d, %s/n", iInt, int2str( iInt, 10, cStr, 10) );

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值