1

いくつかのさまざまなStackoverflowソースを使用して、JAVAを使用した非常に単純なBase64からHexへの変換を実装しました。しかし、問題があったため、16進コードをテキストに変換して正しいことを確認し、インデックス11の文字(左引用符)が翻訳で失われていることを確認して、結果をテストしました。

hexToASCIIが左引用符以外のすべてを変換するのはなぜですか?

public static void main(String[] args){
     System.out.println("Input string:");
     String myString = "AAAAAQEAFxUX1iaTIz8=";
     System.out.println(myString + "\n");

     //toascii
     String ascii = base64UrlDecode(myString);
     System.out.println("Base64 to Ascii:\n" + ascii);

     //tohex
     String hex = toHex(ascii);
     System.out.println("Ascii to Hex:\n" + hex);
     String back2Ascii = hexToASCII(hex);
     System.out.println("Hex to Ascii:\n" + back2Ascii + "\n");
}

public static String hexToASCII(String hex){     
    if(hex.length()%2 != 0){
       System.err.println("requires EVEN number of chars");
       return null;
    }
    StringBuilder sb = new StringBuilder();               
    //Convert Hex 0232343536AB into two characters stream.
    for( int i=0; i < hex.length()-1; i+=2 ){
         /*
          * Grab the hex in pairs
          */
        String output = hex.substring(i, (i + 2));
        /*
         * Convert Hex to Decimal
         */
        int decimal = Integer.parseInt(output, 16);                 
        sb.append((char)decimal);             
    }           
    return sb.toString();
} 

  public static String toHex(String arg) {
    return String.format("%028x", new BigInteger(arg.getBytes(Charset.defaultCharset())));
  }

  public static String base64UrlDecode(String input) {
    Base64 decoder = new Base64();
    byte[] decodedBytes = decoder.decode(input);
    return new String(decodedBytes);
 }

戻り値:

ここに画像の説明を入力してください

4

1 に答える 1

1

それはそれを失いません。デフォルトの文字セットでは理解できません。arg.getBytes()代わりに、文字セットを指定せずに使用してください。

public static String toHex(String arg) {
   return String.format("%028x", new BigInteger(arg.getBytes()));
}

hexToAscIIメソッドも変更します。

public static String hexToASCII(String hex) {
    final BigInteger bigInteger = new BigInteger(hex, 16);
    return new String(bigInteger.toByteArray());
}
于 2012-04-08T02:00:19.233 に答える