2012-04-08 75 views
1

使用一些各種Stackoverflow源我已經使用JAVA實現了一個相當簡單的Base64到Hex的轉換。由於存在問題,我通過嘗試將我的十六進制代碼轉換回文本以確認它是正確的,並且發現索引11(左引號)處的字符在某種程度上正在丟失,從而測試了我的結果。從ascii轉換爲hex並丟失時丟失左引號

爲什麼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

它不會失去它。它不能理解你的默認字符集。改爲使用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()); 
} 
+0

按照指定改變它,這並沒有什麼影響。 – buddyp450 2012-04-08 02:12:12

+0

我更新了我的評論。 – 2012-04-08 02:17:05

+0

謝謝。這消除了我領先的白色空間,但這不是問題。 – buddyp450 2012-04-08 02:32:14