java字元與對應Ascii碼互轉
阿新 • • 發佈:2018-11-07
圖題
程式碼如下:
[java] view plain copy- package main;
- /**
- * Java中將一個字元與對應Ascii碼互轉
- * 1 byte = 8bit 可以表示 0-127
- */
- 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(charToByteAscii('9'
- System.out.println(byteAsciiToChar(57));
- System.out.println(SumStrAscii("19"));
- System.out.println(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 byte charToByteAscii2(char ch){
- byte byteAscii = (byte)ch;
- return byteAscii;
- }
- /**
- * 同理,ascii轉換為char 直接int強制轉換為char
- * @param ascii
- * @return
- */
- public static char byteAsciiToChar(int ascii){
- char ch = (char)ascii;
- return ch;
- }
- /**
- * 求出字串的ASCII值和
- * 注意,如果有中文的話,會把一個漢字用兩個byte來表示,其值是負數
- */
- public static int SumStrAscii(String str){
- byte[] bytestr = str.getBytes();
- int sum = 0;
- for(int i=0;i<bytestr.length;i++){
- sum += bytestr[i];
- }
- return sum;
- }
- }
圖題
程式碼如下:
[java] view plain copy- package main;
- /**
- * Java中將一個字元與對應Ascii碼互轉
- * 1 byte = 8bit 可以表示 0-127
- */
- 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(charToByteAscii('9'));
- System.out.println(byteAsciiToChar(57));
- System.out.println(SumStrAscii("19"));
- System.out.println(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 byte charToByteAscii2(char ch){
- byte byteAscii = (byte)ch;
- return byteAscii;
- }
- /**
- * 同理,ascii轉換為char 直接int強制轉換為char
- * @param ascii
- * @return
- */
- public static char byteAsciiToChar(int ascii){
- char ch = (char)ascii;
- return ch;
- }
- /**
- * 求出字串的ASCII值和
- * 注意,如果有中文的話,會把一個漢字用兩個byte來表示,其值是負數
- */
- public static int SumStrAscii(String str){
- byte[] bytestr = str.getBytes();
- int sum = 0;
- for(int i=0;i<bytestr.length;i++){
- sum += bytestr[i];
- }
- return sum;
- }
- }