Due to the recent service requirements of the project, it is necessary to assemble packets and send them to other terminals. For normal project development, the number operation is string and decimal, but the packets sent to terminals have special requirements, such as hexadecimal or UTF-16 strings, and record the conversion during work

The online conversion tool can compare code conversion with the online conversion tool

1. Convert binary to hexadecimal

public static String twoToSixteen(String s) {
   int data = Integer.valueOf(s, 2);
   String hex = Integer.toHexString(data);
   return hex;
}
Copy the code

2, decimal to binary

public static String tenToTwo(String num) {
    String s = Integer.toBinaryString(Integer.parseInt(num));
    return s;
}
Copy the code

3. Convert hexadecimal to decimal

public static String sixteenToTen(String num) {
    BigInteger lngNum=new BigInteger(num,16);
    return String.valueOf(lngNum.intValue());
}
Copy the code

4. Convert decimal to hexadecimal

public static String tenToSixteen(String str) {
        int data = Integer.parseInt(str);
        String preData = Integer.toHexString(data);
        return preData;
}
Copy the code

5. Convert Chinese characters to hexadecimal numbers

Online tools to check the string (www.mytju.com/classcode/t.)

public static String gbkToUnicode(String str) { String st = ""; ** byte[] by = str.getBytes(" utF-8 "); ** byte[] by = str.getbytes (" utF-8 "); ** byte[] by = str.getbytes (" utF-8 ");  for (int i = 0; i < by.length; i++) { String strs = Integer.toHexString(by[i]); if (strs.length() > 2) { strs = strs.substring(strs.length() - 2); } st += strs; } } catch (Exception e) { e.printStackTrace(); } return st; }Copy the code

6. Convert string to ASCII

View Hex encoding and Hex decoding results onlinestool.chinaz.com/hex

public static String strToASCII(String str) {
    StringBuilder sb = new StringBuilder();
    char[] ch = str.toCharArray();
    for (int i = 0; i < ch.length; i++) {
        int i1 = Integer.valueOf(ch[i]).intValue();
        String s = Integer.toHexString(i1);
        sb.append(s);
    }
    return sb.toString();
}
Copy the code

7, fill the prefix, the number is not enough, the front fill 0

The terminal packet has requirements on the length. If the bits are insufficient, 0 must be added before the bits

Public static String prefixStr(String num, int length) {for (int len = num.length(); len < length; len = num.length()) { num = "0" + num; } return num; }Copy the code