代码之家  ›  专栏  ›  技术社区  ›  Arun Sivan

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

  •  0
  • Arun Sivan  · 技术社区  · 9 年前

    当由索引访问时,需要解码数组中的十六进制代码。用户应该输入数组索引,并将数组中解码的十六进制作为输出。

    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 回复  |  直到 9 年前
        1
  •  1
  •   Rahul Prasad    9 年前

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