Search code examples
carraysstringstrtol

C, how to put number split over an array, into int


Lets say I have char array[10] and [0] = '1', [1] = '2', [2] = '3', etc.

How would i go about creating (int) 123 from these indexes, using C?

I wish to implement this on an arduino board which is limited to just under 2kb of SRAM. so resourcefulness & efficiency are key.


With thanks to Sourav Ghosh, i solved this with a custom function to suit:

long makeInt(char one, char two, char three, char four){
  char tmp[5];
  tmp[0] = one;
  tmp[1] = two;
  tmp[2] = three;
  tmp[3] = four;

  char *ptr;
  long ret;
  ret = strtol(tmp, &ptr, 10);

  return ret;
}

Solution

  • I think what you need to know is strtol(). Read details here.

    Just to quote the essential part

    long int strtol(const char *nptr, char **endptr, int base);

    The strtol() function converts the initial part of the string in nptr to a long integer value according to the given base, which must be between 2 and 36 inclusive, or be the special value 0.