public static String convertStr(String msg) throws UnsupportedEncodingException { //先把字符串按gb2312转成byte数组 byte[] bytes = msg.getBytes("gb2312"); StringBuilder gbString = new StringBuilder(); for (byte b : bytes) { // 再用Integer中的方法,把每个byte转换成16进制输出 String temp = Integer.toHexString(b); //判断进行截取 if(temp.length()>=8){ temp = temp.substring(6, 8); } gbString.append("%" + temp); } return gbString.toString(); }
再main中运行。打印如下