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