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, 2022 in Others by Soham
• 9,710 points
3,699 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, 2022 by Aditya
• 7,680 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, 2022 in Others by Rahul
• 9,680 points
529 views
0 votes
1 answer
+1 vote
1 answer

Between cyber security and CCNA profession which one is best in terms of time to become an expert and salary payment

CCNA professional is more inclined towards the ...READ MORE

answered Dec 18, 2019 in Others by Pri
2,045 views
–2 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, 2022 in Linux Administration by Rahul
• 9,680 points
771 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, 2022 in Linux Administration by Soham
• 9,710 points
959 views
0 votes
1 answer

How does #include <bits/stdc++.h> work in C++? [duplicate]

#include <bits/stdc++.h> is a precompiled header implementation ...READ MORE

answered Jun 21, 2022 in C++ by Damon
• 4,960 points
8,542 views
0 votes
0 answers

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

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

Dec 14, 2022 in Linux Administration by erzan
• 630 points
694 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, 2022 in Others by Aditya
• 7,680 points
2,141 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, 2022 in Others by Aditya
• 7,680 points
714 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP