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

时间:2015-07-19 20:19:28

标签: java arrays hex decoding

当通过index访问时,需要解码数组中的十六进制代码。用户应输入数组索引并在数组中作为输出获得十六进制解码。

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"));

1 个答案:

答案 0 :(得分:1)

从用户获取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();
            }
        }