Convert char to int in C and C

0 votes
How do I convert a char to an int in C and C++?
Feb 17 in Others by Soham
• 8,730 points
92 views

1 answer to this question.

0 votes

In order 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 */

This is due to the reason that 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.

answered Feb 17 by Aditya
• 7,280 points

Related Questions In Others

0 votes
1 answer

Easiest way to convert int to string in C++

The C++11 version has introduced the std::stoi ...READ MORE

answered Feb 10 in Others by Rahul
• 8,980 points
19 views
0 votes
1 answer
+1 vote
1 answer
0 votes
0 answers
0 votes
0 answers

How to compile for Windows on Linux with gcc/g++?

I have written some effects in C++ ...READ MORE

Apr 13 in Linux Administration by Rahul
• 8,980 points
20 views
0 votes
0 answers

How to implement getch() function of C in Linux?

In TurboC++, I can use the getch() ...READ MORE

Apr 14 in Linux Administration by Soham
• 8,730 points
13 views
0 votes
1 answer

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

answered Sep 11, 2018 in Python by Priyaj
• 58,060 points
178 views
0 votes
1 answer

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

answered Sep 21, 2018 in Python by Priyaj
• 58,060 points
1,328 views
0 votes
1 answer

How to get current time and date in Android

In order to get the current date ...READ MORE

answered Feb 23 in Others by Aditya
• 7,280 points
84 views
0 votes
1 answer

How do I get the current date and time in PHP?

The time would go by your server ...READ MORE

answered Feb 16 in Others by Aditya
• 7,280 points
17 views
webinar REGISTER FOR FREE WEBINAR X
Send OTP
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP