package com.example.writeepc;

/**
 * @author: wangh
 * @description: Ass
 * @date: 2019/06/20-15:18
 */
public class ASCIIUtil {

    //    String明文转ASCII码hex字符串,一个明文字符生成两个字符表示的16进制ASCII码
    public static String str2Hex(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            // 这里的第二个参数16表示十六进制
            sb.append(Integer.toString(c, 16));
            // 或用toHexString方法直接转成16进制
            // sb.append(Integer.toHexString(c));
        }
        return sb.toString();
    }

    //    ASCII码hex字符串转String明文
    public static String hex2Str(String hex) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 2) {
            String h = hex.substring(i, (i + 2));
            int decimal = Integer.parseInt(h, 16);
            sb.append((char) decimal);
        }
        return sb.toString();

    }
    public static String hexTo4ZN(String hex) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hex.length() - 1; i += 4) {
            String h =  hex.substring(i, (i + 4));

            sb.append((char) Integer.parseInt(h, 16));
        }
        return sb.toString();

    }


    public static String str4Hex(String str) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            String s = Integer.toString(str.charAt(i), 16);
            sb.append(s.length()==2?"00"+s:s);
        }
        return sb.toString();
    }
    public static String convertToAscii(String chineseText) {
        StringBuilder asciiText = new StringBuilder();

        for (int i = 0; i < chineseText.length(); i++) {
            char c = chineseText.charAt(i);
            int asciiValue = (int) c;

            asciiText.append(asciiValue).append(" ");
        }

        return asciiText.toString().trim();
    }
}
