【问题标题】:Losing left quote mark when converting from ascii to hex and back again从 ascii 转换为十六进制并再次转换回来时丢失左引号
【发布时间】:2012-04-21 00:48:31
【问题描述】:

使用一些不同的 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);
 }

返回:

【问题讨论】:

    标签: java hex base64 ascii


    【解决方案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());
    }
    

    【讨论】:

    • 按照您的要求更改了它,这没有影响任何事情。
    • 谢谢。这消除了我的主要空白,但这不是问题。
    猜你喜欢
    • 2021-02-25
    • 2021-12-17
    • 2018-12-06
    • 2017-08-28
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多