public class GetCharAscii {
/*0-9对应Ascii 48-57
*A-Z 65-90
*a-z 97-122
*第33~126号(共94个)是字符,其中第48~57号为0~9十个阿拉伯数字
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("char --> byte ascii:" + charToByteAscii('8'));
System.out.println("char --> int ascii:" + charToByteAscii2('8'));
System.out.println("ascii to char:" + byteAsciiToChar(56));
System.out.println("int --> sum:" + SumStrAscii("19"));
System.out.println("china --> sum:" + SumStrAscii("你"));
}
/**
* 方法一:将char 强制转换为byte
* @param ch
* @return
*/
public static byte charToByteAscii(char ch){
byte byteAscii = (byte)ch;
return byteAscii;
}
/**
* 方法二:将char直接转化为int,其值就是字符的ascii
* @param ch
* @return
*/
public static Integer charToByteAscii2(char ch){
int byteAscii = (int)ch;
return byteAscii;
}
/**
* 同理,ascii转换为char 直接int强制转换为char
* @param ascii
* @return
*/
public static char byteAsciiToChar(int ascii){
char ch = (char)ascii;
return ch;
}
/**
* 求出字符串的ASCII值和
* 注意,如果有中文的话,GBK
* GBK会把一个汉字用两个byte来表示,其值是负数
* UTF-8会把一个汉字用三个byte来表示,其值是负数
*/
public static int SumStrAscii(String str){
byte[] bytestr = str.getBytes();
int sum = 0;
System.out.print("----\"" + str + "\"对应的byte值:");
for(int i=0;i<bytestr.length;i++){
System.out.print(bytestr[i]+" ");
sum += bytestr[i];
}
System.out.println();
return sum;
}
}
结果:
char --> byte ascii:56
char --> int ascii:56
ascii to char:8
----"19"对应的byte值:49 57
int --> sum:106
----"你"对应的byte值:-28 -67 -96
china --> sum:-191
ASCII码对应的值:https://wenku.baidu.com/view/b73fb769e3bd960590c69ec3d5bbfd0a7856d549