如何在 java 中解码数组中的十六进制代码

How to decode hex code in an array in java

当被index.User访问时需要解码数组中的十六进制代码应输入数组索引并将数组中的解码十六进制作为输出。

import java.util.Scanner;

  class Find {

  static String[] data={ " \x6C\x65\x6E\x67\x74\x68",
                       "\x73\x68\x69\x66\x74"

                           //....etc upto 850 index

                        };

  public static void main(String[] args) {

  Scanner in = new Scanner(System.in);

  System.out.println("Enter a number");

  int s = in.nextInt();

  String decodeinput=data[s];

                          // need to add some code here 
                          //to decode hex and store to a string decodeoutput to print it

  String decodeoutput=......

  System.out.println();
                                          }
              }

如何使用...

              String hexString ="some hex string";    

              byte[] bytes = Hex.decodeHex(hexString .toCharArray());

              System.out.println(new String(bytes, "UTF-8"));

从用户获取s的值后追加以下代码。 Imp:请使用 camelCase 约定命名变量,如上所述。为了方便起见,我只是继续使用与您相同的名称。

    if (s>= 0 && s < data.length) {
            String decodeinput = data[s].trim();

            StringBuilder decodeoutput = new StringBuilder();

            for (int i = 2; i < decodeinput.length() - 1; i += 4) {
                // Extract the hex values in pairs
                String temp = decodeinput.substring(i, (i + 2));
                // convert hex to decimal equivalent and then convert it to character
                decodeoutput.append((char) Integer.parseInt(temp, 16));
            }
            System.out.println("ASCII equivalent : " + decodeoutput.toString());
     }

或者,只需完成您正在做的事情:

/*      import java.io.UnsupportedEncodingException;
        import org.apache.commons.codec.DecoderException;
        import org.apache.commons.codec.binary.Hex; //present in commons-codec-1.7.jar
*/
        if (s>= 0 && s < data.length)  {
            String hexString =data[s].trim();
            hexString = hexString.replace("\x", "");
            byte[] bytes;
            try {
                bytes = Hex.decodeHex(hexString.toCharArray());
                System.out.println("ASCII equivalent : " + new String(bytes, "UTF-8"));
            } catch (DecoderException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }