java 字符串进制转换

1. 字符串、16进制互转(带中文)

import java.io.UnsupportedEncodingException;
import snmp.test.demo.util.StringUtils;

public class Test {

    public static void main(String[] args) {
        System.out.println("==========str=>hex=========");
        System.out.println(toHexStr("测试-CS"));
        System.out.println("==========hex=>str=========");
        System.out.println(deUnicode(toHexStr("测试-CS")));
    }
    
    //带中文
    public static String toHexStr(String s){
        String ss = s;
        byte[] bt = new byte[0];
        try {
            bt = ss.getBytes("GBK");
        }catch (Exception e){
            e.printStackTrace();
        }
        
        String s1 = "";
        for (int i = 0; i < bt.length; i++){
            String tempStr = Integer.toHexString(bt[i]);
            if (tempStr.length() > 2)
                tempStr = tempStr.substring(tempStr.length() - 2);
            s1 = s1 + tempStr + "";
        }
        return s1.toUpperCase();
    }
    
    //带中文
    public static String deUnicode(String str) {
        if(StringUtils.isEmpty(str)) {
            return null;
        }
        str=str.toLowerCase().replaceAll(":", "");
        byte[] bytes = new byte[str.length() / 2];
        byte tempByte = 0;
        byte tempHigh = 0;
        byte tempLow = 0;
            for (int i = 0, j = 0; i < str.length(); i += 2, j++) {
                tempByte = (byte) (((int) str.charAt(i)) & 0xff);
                if (tempByte >= 48 && tempByte <= 57) {
                    tempHigh = (byte) ((tempByte - 48) << 4);
                } else if (tempByte >= 97 && tempByte <= 101) {
                    tempHigh = (byte) ((tempByte - 97 + 10) << 4);
                }else {
                    tempLow = (byte) ((tempByte - 97 + 10) << 4);
                }
                tempByte = (byte) (((int) str.charAt(i + 1)) & 0xff);
                if (tempByte >= 48 && tempByte <= 57) {
                    tempLow = (byte) (tempByte - 48);
                } else if (tempByte >= 97 && tempByte <= 101) {
                    tempLow = (byte) (tempByte - 97 + 10);
                }else {
                    tempLow = (byte) (tempByte - 97 + 10);
                }
                bytes[j] = (byte) (tempHigh | tempLow);
            }
            String result = null;
            try {
                result = new String(bytes, "GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return result;
        }
}

本文参考地址:

https://blog.csdn.net/qq_16165281/article/details/80427774,(字符串转16进制)

https://www.cnblogs.com/cnndevelop/p/5220958.html ,(16进制字符串转换成汉字