Today, in the project, we want to convert the hexadecimal string into Chinese characters, but the conversion is garbled. Later, we put the Conversion Function in the java project to perform normal conversion, in general, the first thought of garbled characters is the encoding method. I used to use UTF-8 for a long time. I checked the information and saw someone saying that UTF-8 didn't work. I used GB2312. I changed it and it worked really well. The Code is as follows:
Package com. quickpasslibrary. utils; import java. io. byteArrayOutputStream;/*** conversion between hexadecimal formats * @ author implements Zhangjie **/public class HexadecimalConver {private static String hexString = "0123456789 ABCDEF"; public static String toStringHex (String s) {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, "GB2312");} catch (Exception e1) {e1.printStackTrace ();} return s ;} /*** encode the String into a hexadecimal number, applicable to all characters (including Chinese) */public static String encode (String str) {// obtain byte array byte [] bytes = str according to the default encoding. getBytes (); StringBuilder sb = new StringBuilder (bytes. length * 2); // splits each byte in the byte array into two hexadecimal integers for (int I = 0; I
> 4); sb. append (hexString. charAt (bytes [I] & 0x0f)> 0);} return sb. toString ();}/*** decodes a hexadecimal number into a String, applicable to all characters (including Chinese) */public static String decode (String bytes) {ByteArrayOutputStream baos = new ByteArrayOutputStream (bytes. length ()/2); // Assemble every two hexadecimal integers into one byte for (int I = 0; I