Converting character types to int or other integer types

This knowledge point is not often used, so I feel that it is easy to ignore and forget, but it is the basic content of java. The difference is written below. Most of the text below is pasted from others, but I have forgotten the source.

1. The conversion of char to int refers to the conversion of numeric characters to integers, because characters are divided into numeric characters (0-9) and non-numeric characters, and we generally say that the conversion of characters to integers refers to the conversion of numeric characters to integers . The process of converting characters to integers is to first convert the character type into a string, and then convert the string into an integer. Assuming that c is of type char, i is of type int, and s is of type String, then the process of converting c to type of String is: s=String.valueOf(c); i=Integer.parseInt(s); i saves the value of c converted to int. For example, after the character '0' is converted into an integer, it is 0. If a non-numeric character cannot be converted into an integer, an error will occur during the conversion process.


2. The concept that is easy to be confused in char to int: digital characters actually contain two layers of digital concepts, one is the number represented by itself, and the other is the character encoding used when it is saved . Many people easily confuse these two concepts, such as character The number '1' itself represents is 1, and her character code (ascii code, Unicode code, etc.) is 49. When char is converted to int, is the value 1 or the code value 49? The answer is the value of 1, which is the number itself, which is why only numeric characters can be converted to integers. Then, if I want to use the encoding value of the character, it is very simple, just add (int) directly in front of the character, for example i=(int) c; I can extract the character encoding value of the character c and assign it to the integer i , if c='1', then after the assignment, i is equal to 49, not 1. At the same time, the char type can be used directly as an integer, for example: char c='1'; then after int i=c+1, the value of i is 50, not 2, at this time, the encoding value of the character is used to calculate . If c='a', since the character encoding of a (determined by the character encoding, the character encoding in java is unicode encoding) is 61, so after int i=c+1, the value of i is 62.

In summary, the unicode code value is obtained by using forced conversion. To get its own value, you need to convert the string first and then convert the number;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325522343&siteId=291194637