Search code examples
ccastingkernel

C string to int without any libraries


I'm trying to write my first kernel module so I'm not able to include libraries for atoi, strtol, etc. How can I convert a string to int without these built-in functions? I tried:

int num;
num = string[0] - '0';

which works for the first character, but if I remove the [0] to try and convert the full string it gives me a warning: assignment makes integer from pointer without a cast. So what do I do?


Solution

  • When creating your own string to int function, make sure you check and protect against overflow. For example:

    /* an atoi replacement performing the conversion in a single
       pass and incorporating 'err' to indicate a failed conversion.
       passing NULL as error causes it to be ignored */
    int strtoi (const char *s, unsigned char *err)
    {
        char *p = (char *)s;
        int nmax = (1ULL << 31) - 1;    /* INT_MAX  */
        int nmin = -nmax - 1;           /* INT_MIN  */
        long long sum = 0;
        char sign = *p;
    
        if (*p == '-' || *p == '+') p++;
    
        while (*p >= '0' && *p <= '9') {
            sum = sum * 10 - (*p - '0');
            if (sum < nmin || (sign != '-' && -sum > nmax)) goto error;
            p++;
        }
    
        if (sign != '-') sum = -sum;
    
        return (int)sum;
    
    error:
    
        fprintf (stderr, "strtoi() error: invalid conversion for type int.\n");
        if (err) *err = 1;
        return 0;
    }