How convert a char[] string to int in the Linux kernel?

前端 未结 6 1103
暖寄归人
暖寄归人 2020-12-09 04:07

How convert char[] to int in linux kernel

with validation that the text entered is actually an int?

int procfile_write(struct file *file, const char          


        
6条回答
  •  抹茶落季
    2020-12-09 04:30

    Because of the unavailability of a lot of common function/macros in linux kernel, you can not use any direct function to get integer value from a string buffer.

    This is the code that I have been using for a long time for doing this and it can be used on all *NIX flavors (probably without any modification).

    This is the modified form of code, which I used a long time back from an open source project (don't remember the name now).

    #define ISSPACE(c)  ((c) == ' ' || ((c) >= '\t' && (c) <= '\r'))
    #define ISASCII(c)  (((c) & ~0x7f) == 0)
    #define ISUPPER(c)  ((c) >= 'A' && (c) <= 'Z')
    #define ISLOWER(c)  ((c) >= 'a' && (c) <= 'z')
    #define ISALPHA(c)  (ISUPPER(c) || ISLOWER(c))
    #define ISDIGIT(c)  ((c) >= '0' && (c) <= '9')
    
    unsigned long mystr_toul (
        char*   nstr,
        char**  endptr,
        int base)
    {
    #if !(defined(__KERNEL__))
        return strtoul (nstr, endptr, base);    /* user mode */
    
    #else
        char* s = nstr;
        unsigned long acc;
        unsigned char c;
        unsigned long cutoff;
        int neg = 0, any, cutlim;
    
        do
        {
            c = *s++;
        } while (ISSPACE(c));
    
        if (c == '-')
        {
            neg = 1;
            c = *s++;
        }
        else if (c == '+')
            c = *s++;
    
        if ((base == 0 || base == 16) &&
            c == '0' && (*s == 'x' || *s == 'X'))
        {
            c = s[1];
            s += 2;
            base = 16;
        }
        if (base == 0)
            base = c == '0' ? 8 : 10;
    
        cutoff = (unsigned long)ULONG_MAX / (unsigned long)base;
        cutlim = (unsigned long)ULONG_MAX % (unsigned long)base;
        for (acc = 0, any = 0; ; c = *s++)
        {
            if (!ISASCII(c))
                break;
            if (ISDIGIT(c))
                c -= '0';
            else if (ISALPHA(c))
                c -= ISUPPER(c) ? 'A' - 10 : 'a' - 10;
            else
                break;
    
            if (c >= base)
                break;
            if (any < 0 || acc > cutoff || (acc == cutoff && c > cutlim))
                any = -1;
            else
            {
                any = 1;
                acc *= base;
                acc += c;
            }
        }
    
        if (any < 0)
        {
            acc = INT_MAX;
        }
        else if (neg)
            acc = -acc;
        if (endptr != 0)
            *((const char **)endptr) = any ? s - 1 : nstr;
        return (acc);
    #endif
    }
    

提交回复
热议问题