Simon.
Simon.

Reputation: 1896

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;
}

Upvotes: 0

Views: 487

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

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.

Upvotes: 4

DrKoch
DrKoch

Reputation: 9772

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
}

Upvotes: 2

Yasir Majeed
Yasir Majeed

Reputation: 741

int i = ((array[0] << 24) & 0xff000000) |
                ((array[1] << 16) & 0x00ff0000) |
                ((array[2] << 8) & 0x0000ff00) |
                ((array[3] << 0) & 0x000000ff);

This should work

Upvotes: 2

Related Questions