📜  converte char int (1)

📅  最后修改于: 2023-12-03 15:00:01.967000             🧑  作者: Mango

Convert char to int in Programming

In programming, it is often required to convert a character to an integer. This can be achieved using various methods in different programming languages. In this article, we will explore how to convert a char to an int in programming.

Converting char to int in C Programming

In C programming language, a char can be converted to an int by simply assigning the char to an int variable. The ASCII value of the char is assigned to the int variable. Here is an example:

char c = 'A'; // Initializing a char variable to 'A'
int i = c; // Converting char to int

In the above example, the char 'A' is assigned to variable c. Then, the char c is assigned to an int variable i by simply using the = operator. The ASCII value of 'A' which is 65 is assigned to variable i.

Converting char to int in Java Programming

In Java programming language, a char can be converted to an int using the (int) casting operator or by using the Character.getNumericValue() method. Here is an example:

char c = 'A'; // Initializing a char variable to 'A'
int i1 = (int) c; // Using casting operator to convert char to int
int i2 = Character.getNumericValue(c); // Using getNumericValue() method to convert char to int

In the above example, the char 'A' is assigned to variable c. Then, the char c is assigned to an int variable i1 by using the (int) casting operator. The ASCII value of 'A' which is 65 is assigned to variable i1. Another int variable i2 is assigned the numeric value of the char 'A' using the Character.getNumericValue() method. The numeric value of 'A' which is 10 is assigned to variable i2.

Conclusion

Converting a char to an int is a simple task in programming. It can be achieved using various methods in different programming languages as shown in the examples above. Remember that the ASCII value of the char is assigned to the int variable when a char is converted to an int.