首页 > 编程语言 > 详细

C语言-数字字符串转换成这个字符串对应的数字(十进制、十六进制)

时间:2019-06-20 19:39:14      阅读:149      评论:0      收藏:0      [点我收藏+]

数字字符串转换成这个字符串对应的数字(十进制、十六进制)

 

(1)数字字符串转换成这个字符串对应的数字(十进制)

要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

提示:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。

思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

代码如下:

#include <stdio.h>
#include <assert.h>
int my_atoi(char *str)
{
    int n = 0;
    int flag = 0;
    assert(str);
    if(*str == -)
    {
        flag = 1;
        str++;
    }
    while(*str >= 0 && *str <= 9)
    {
        n = n*10 + (*str - 0);
        str++;
    }
    if(flag == 1)
    {
        n = -n;
    }
    return n;
}
int main ()
{
    char a[] = "12";
    char b[] = "-123";
    printf("%d\n%d\n",my_atoi(a),my_atoi(b));
    return 0;
}

 

(2)数字字符串转换成这个字符串对应的数字(十六进制)

要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

提示:你每发现一个数字,把当前值乘以16,并把这个值和新的数字所代表的值相加。

思路:字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。 

代码如下:

#include <stdio.h>
#include <assert.h>
#include <iostream>

using namespace std;

int change(char* str)
{
    assert(str);
    int result = 0;
    int flag = 0;

    if (*str == -) 
    {
        flag = 1;
        str++;
    }

    while (*str) 
    {
        if (*str >= 0 && *str <= 9)
            result = result * 16 + (*str - 0);
        else if (*str >= a && *str <= f)
            result = result * 16 + (*str - a + 10);
        else if (*str >= A && *str <= F)
            result = result * 16 + (*str - A + 10);
        else {
            cout << "非法字符!" << endl;
            return 0;
        }
        str++;
    }

    if (flag == 1) result = -result;

    return result;
}

int main()
{
    char str[] = "-16";
    int res = change(str);
    cout << res << endl;

    return 0;
}

 

C语言-数字字符串转换成这个字符串对应的数字(十进制、十六进制)

原文:https://www.cnblogs.com/zkfopen/p/11060685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!