Reputation: 1896
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
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 innptr
to along int
eger value according to the givenbase
, which must be between2
and36
inclusive, or be the special value0
.
Upvotes: 4
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
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