字符轉數字(包含負數)

如下demo爲在內核中將字符轉爲數字。其原理就是將每一個字符單獨拿出來然後重新拼接相加。正負值通過flag控制。

#include <stdio.h>
#include <string.h>
#include <assert.h>
int tran(char *s)
{
    assert(s && strlen(s));
    int flag = 1;
    int ret = 0;
    while(*s == '-' && ++s && (flag = -1) == 1 || *s! = '\0')
    {
        if(*s>='0' && *s<='9')
        {
            ret = 10*ret + (*s++-'0');
        }
        else
        {
            ++s;
        }
    }
    return flag*ret;
}
static void main(void)
{
    char buf[]="-1500";
    printf("%d\n", tran(buf));
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章