Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char to int in C and C++

Tags:

c++

c

gcc

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

like image 689
mainajaved Avatar asked Feb 17 '11 13:02

mainajaved


People also ask

Is char and int in C same?

char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers. int: As the name suggests, an int variable is used to store an integer. float: It is used to store decimal numbers (numbers with floating point value) with single precision.

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. The function stops reading the input string at the first character that it cannot recognize as part of a number.

What is Strtol function in C?

The strtol library function in C converts a string to a long integer. The function works by ignoring any whitespace at the beginning of the string, converting the next characters into a long integer, and stopping when it comes across the first non-integer character.


2 Answers

Depends on what you want to do:

to read the value as an ascii code, you can write

char a = 'a'; int ia = (int)a;  /* note that the int cast is not necessary -- int ia = a would suffice */ 

to convert the character '0' -> 0, '1' -> 1, etc, you can write

char a = '4'; int ia = a - '0'; /* check here if ia is bounded by 0 and 9 */ 

Explanation:
a - '0' is equivalent to ((int)a) - ((int)'0'), which means the ascii values of the characters are subtracted from each other. Since 0 comes directly before 1 in the ascii table (and so on until 9), the difference between the two gives the number that the character a represents.

like image 62
Foo Bah Avatar answered Oct 05 '22 14:10

Foo Bah


Well, in ASCII code, the numbers (digits) start from 48. All you need to do is:

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. 
like image 37
Vlad Isoc Avatar answered Oct 05 '22 15:10

Vlad Isoc