1. 程式人生 > 其它 >java編碼轉換、字串轉成ASCII

java編碼轉換、字串轉成ASCII

技術標籤:Javaunicode字串ASCII


/**
 * 編碼轉換
 * @Author: szw
 * @Date: 2020/12/13 23:57
 */
public class CodeUtil {

    public static void main(String[] args) {
        String str = "{name123password123456}";
        String asciiResult = stringToAscii(str);
        System.out.println(asciiResult);
        String stringResult = asciiToString(asciiResult);
        System.out.println(stringResult);

        String str2 = "漢語pinyin";
        String unicode = stringToUnicode(str2);
        System.out.println("字串轉unicode結果:" + unicode);
        String s = unicodeToString(unicode);
        System.out.println("unicode轉字串結果:" + s);
    }

    /**
     * 將字串轉成ASCII
     */
    public static String stringToAscii(String value) {
        StringBuffer sbu = new StringBuffer("");
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
        }
        return sbu.toString();
    }

    /**
     * 將ASCII轉成字串
     */
    public static String asciiToString(String value) {
        StringBuffer sbu = new StringBuffer("");
        String[] chars = value.split(",");
        for (int i = 0; i < chars.length; i++) {
            sbu.append((char) Integer.parseInt(chars[i]));
        }
        return sbu.toString();
    }

    /**
     * 字串轉unicode
     */
    public static String stringToUnicode(String str) {
        StringBuffer sb = new StringBuffer("");
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            sb.append("\\u" + Integer.toHexString(c[i]));
        }
        return sb.toString();
    }

    /**
     * unicode轉字串
     */
    public static String unicodeToString(String unicode) {
        StringBuffer sb = new StringBuffer("");
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int index = Integer.parseInt(hex[i], 16);
            sb.append((char) index);
        }
        return sb.toString();
    }

}