从ascii转换为十六进制并再次返回时丢失左引号

时间:2012-04-08 01:46:59

标签: java hex base64 ascii

使用一些不同的Stackoverflow源我使用JAVA实现了一个相当简单的Base64到Hex转换。由于一个问题,我测试了我的结果,试图将我的十六进制代码转换回文本以确认它是正确的,并发现索引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);
 }

返回:

enter image description here

1 个答案:

答案 0 :(得分: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());
}