【网络编程】中文字符、时间等编码转换

2024-05-21 16:27:56 浏览数 (3)

GB2312编码转化为汉字

代码语言:javascript复制
    /**
     * 将GB2312编码(十六进制)转换成汉字
     */
    public static String gbkHexToString(String string) throws Exception {
        byte[] bytes = new byte[string.length() / 2];
        for (int i = 0; i < bytes.length; i  ) {
            byte high = Byte.parseByte(string.substring(i * 2, i * 2   1), 16);
            byte low = Byte.parseByte(string.substring(i * 2   1, i * 2   2), 16);
            bytes[i] = (byte) (high << 4 | low);
        }
        String result = new String(bytes, "gbk");
        return result;
    }

ASCII编码(16进制)转字符串

代码语言:javascript复制
    public static String ascHextoString(String s1) {
        // 去除空格
        String ss[] = s1.trim().split("  ");
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < ss.length; i  ) {
            sb.append(ss[i]);
        }
        String s = sb.toString();

        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i  ) {
            try {
                baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2   2), 16));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            s = new String(baKeyword, "ASCII");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return s;
    }

MD5加密字符串

代码语言:javascript复制
public static String encodeMD5(String s) {
        if (isEmpty(s)) {
            return null;
        }
        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ex) {
            // ignore ex
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        md.update(s.getBytes());
        byte[] datas = md.digest();
        int len = datas.length;
        char str[] = new char[len * 2];
        int k = 0;
        for (int i = 0; i < len; i  ) {
            byte byte0 = datas[i];
            str[k  ] = hexDigits[byte0 >>> 4 & 0xf];
            str[k  ] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

转换时间

代码语言:javascript复制
    /**
     * 时间转换为4字节ID YYDDMMHHMMSS
     * 272EDBB9 -> 191223134657
     */
    public static String IDToTime(String id) {
        long timeid = Long.valueOf(id, 16).longValue();
        long year = ((timeid >> 26) & 0x1f)   10;
        long mon = (timeid >> 22) & 0x0f;
        long day = (timeid >> 17) & 0x1f;
        long hour = (timeid >> 12) & 0x1f;
        long min = (timeid >> 6) & 0x3f;
        long sec = timeid & 0x3f;
        long date = year * 10000   mon * 100   day;
        long time = hour * 10000   min * 100   sec;
        String StringTimer = addZeroForNum(String.valueOf(time), 6, true);
        String datetime = String.valueOf(date)   StringTimer;
        return datetime;
    }

0 人点赞