java中數字與ASCII碼的相互轉換的代碼

jopen 9年前發布 | 4K 次閱讀 Java

在編程中經常會用到將字符串數字轉換成ASCII值,前一段時間遇到了這個問題,下面是解決問題的代碼,希望能夠幫助到有需要的猿友們

//測試demo
public static void main(String[] args) {
         int a=91151561;
         for (byte b : String.valueOf(a).getBytes()) {
char c=(char) (b + 48); String str=String.valueOf(c); System.out.print(str.toUpperCase());
}

}


//數字與ASCII碼之間互轉換 public class TestConvert {

// 將字母轉換成數字_1  
public static String t1(String input) {  
    String reg = "[a-zA-Z]";  
    StringBuffer strBuf = new StringBuffer();  
    input = input.toLowerCase();  
    if (null != input && !"".equals(input)) {  
        for (char c : input.toCharArray()) {  
            if (String.valueOf(c).matches(reg)) {  
                strBuf.append(c - 96);  
            } else {  
                strBuf.append(c);  
            }  
        }  
        return strBuf.toString();  
    } else {  
        return input;  
    }  
}  

// 將字母轉換成數字  
public static void letterToNum(String input) {  
    for (byte b : input.getBytes()) {  
        System.out.print(b - 96);  
    }  
}  

// 將數字轉換成字母  
public static void numToLetter(String input) {  
    for (byte b : input.getBytes()) {  
        System.out.print((char) (b + 48));  
    }  
}  

public static void main(String[] args) {  
    String i1 = "abcdef";  
    String i2 = "123456";  
    letterToNum(i1);  
    System.out.println();  
    numToLetter(i2);  
}  

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!