Search code examples
concatenation

Concatenate certain arrays elements into a int in Arduino


I have an array of 7 elements, which contains some values combinations.

for example, I need to transform from 2nd to 4th into a 234 int.

char myarray[5] = {'1','2','3','4','5','6','7'};

int i = atoi(myarray);

printf("%d\n", i);

This way, it returns the int, but all array values...1234567


Solution

  • Ok, try this:

    int atoisub(char *s, int start, int end)
    {
        int rv = 0;
        for (int i = start; i < end; ++i) {
            rv = rv * 10 + (s[i] - '0');
        }
        return rv;
    }
    

    Call as atoisub(myarray, 1, 4). There's no error checking for non-digit characters or invalid parameters.