Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char to integer in C? [duplicate]

Tags:

c

char

int

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.

like image 531
Cute Avatar asked May 15 '09 12:05

Cute


People also ask

Can we convert char to int in c?

We can convert char to int by negating '0' (zero) character. char datatype is represented as ascii values in c programming. Ascii values are integer values if we negate the '0' character then we get the ascii of that integer digit.

What Atoi does in c?

The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type.

How do I convert a char to an int in C++?

int x = (int)character - 48; Or, since the character '0' has the ASCII code of 48, you can just write: int x = character - '0'; // The (int) cast is not necessary.


1 Answers

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.

like image 127
Paul Tomblin Avatar answered Oct 14 '22 20:10

Paul Tomblin