0

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;
}
Simon.
  • 1,886
  • 5
  • 29
  • 62

3 Answers3

4

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.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
2
int i = ((array[0] << 24) & 0xff000000) |
                ((array[1] << 16) & 0x00ff0000) |
                ((array[2] << 8) & 0x0000ff00) |
                ((array[3] << 0) & 0x000000ff);

This should work

Yasir Majeed
  • 739
  • 3
  • 12
2

if you have no library with strtol()or atoi() available use this:

int result = 0;
for(char* p = array; *p; )
{    
    result += *p++ - '0';
    if(*p) result *= 10; // more digits to come
}
DrKoch
  • 9,556
  • 2
  • 34
  • 43