How to convert char to integer in C?

CCharInt

C Problem Overview


> Possible Duplicates:
> How to convert a single char into an int
> Character to integer in C

Can any body tell me how to convert a char to int?

char c[]={'1',':','3'};
	
int i=int(c[0]);
	
printf("%d",i);

When I try this it gives 49.

C Solutions


Solution 1 - C

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Solution 2 - C

The standard function atoi() will likely do what you want.

A simple example using "atoi":

#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int useconds = atoi(argv[1]); 
    usleep(useconds);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCuteView Question on Stackoverflow
Solution 1 - CPaul TomblinView Answer on Stackoverflow
Solution 2 - CFrans BoumaView Answer on Stackoverflow