1

I'm trying to parse a char string into an INT.

If I had...

unsigned char color[] = "255"

And wanted to parse this into an INT. How would I go about doing this?

I tried...

unsigned char *split;

split = strtok(color," ,.-");
while(split != NULL)
{
    split = strok(NULL, " ,.-);
}

This just gives me the value 255 for split now.

I feel like I need something like...

int y = split - '0';   //but this makes an INT pointer without a cast
0

2 Answers 2

5

To convert a string to integer, call strtol:

char color[] = "255";
long n;
char *end = NULL;
n = strtol(color, &end, 10);
if (*end == '\0') {
    // convert was successful
    // n is the result
}
Sign up to request clarification or add additional context in comments.

1 Comment

@user3622460 glad to know it helps.
0

If you want to convert without calling strtol you can scan the color array and compare each char against '0' to get the corresponding numeric value, then add the result properly multiplied by a power of 10, i.e.

int i = 0, strlen = 0, result = 0;
while (color[i++]) strlen++;
for (i = 0; i<strlen; i++)
{
    result += (color[i] - '0')*pow(10,strlen-1-i);
}

1 Comment

I don't get the impression "without strtol" was OPs idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.