Int char conversion character type and

char[] ch = {'a', 'b', 'c'};
System.out.println(ch[0]);//a
char fg = 97;
System.out.println(fg);//a
char f = '9';
System.out.println(f);//9
//int 转换为char型;
// int类型转char类型,将数字加一个‘0’,并强制类型转换为char即可。
int num = 9;
char cNumber = (char) (num + '0');//为啥要加‘0’,'0'会自动转换为int型进行计算
System.out.println(cNumber);//9

//char转换为int

char cc = '6';
int number = cc - '0';//为啥要减去0
System.out.println(number);//6


System.out.println(Integer.parseInt(String.valueOf(cc)));//6

 

Explanation: Why add and subtract problems 0 0:

1) in the computer, 0-127 represent numbers and characters,

Here it is assumed that the character '0' ------ '9',

   Int corresponding to the numeral 48. -------- 57

Then you want to convert char int, and '0' is an offset is just representative of the number.

Int desired conversion of char, is converted into a digital character like 9 9, plus '0', '0' is involved in computing, automatically converted to an int, 48 + 9 = 57, and then cast into char, character 9 is

"Upward compatible" - i.e.: the different data types involved in computing, data type to be cast, the direction changing

(unsigned)char,(unsigned)short->int->unsigned->long->unsigned long->float->double->longdouble。

reference:

https://www.cnblogs.com/hongten/archive/2013/03/24/hongten_java_char_int.html

https://www.cnblogs.com/yongh/p/9688259.html

Published 45 original articles · won praise 8 · views 5860

Guess you like

Origin blog.csdn.net/wenyunick/article/details/103521918