2012-10-13 21 views
2

请帮我在一个十六进制串转换为Base64转换十六进制字符串为Base64

这里是哪里半寸我得到异常

String hexString = "bf940165bcc3bca12321a5cc4c753220129337b48ad129d880f718d147a2cd1bfa79de92239ef1bc06c2f05886b0cd5d"; 

private static String ConvertHexStringToBase64(String hexString) { 
    System.out.println(hexString); 
    if ((hexString.length()) % 2 > 0) 
     throw new NumberFormatException("Input string was not in a correct format."); 
    byte[] buffer = new byte[hexString.length()/2]; 
     int i = 0; 
     while (i < hexString.length()) 
     { 
      buffer[i/2] = Byte.parseByte(hexString.substring(i, 2)); 
      i += 2; 
     } 
     System.out.println("hexSring"+hexString+"afterconverttobase64"+Base64.encodeBase64String(buffer)); 
     return Base64.encodeBase64String(buffer); 

} 

我在这里得到一个异常:bf940165bcc3bca12321a5cc4c753220129337b48ad129d880f718d147a2cd1bfa79de92239ef1bc06c2f05886b0cd5d Exception in thread "main" java.lang.NumberFormatException: For input string: "bf" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Integer.parseInt(Integer.java:449) at java.lang.Byte.parseByte(Byte.java:151) at java.lang.Byte.parseByte(Byte.java:108) at com.motorola.gst.DecryptTest3.ConvertHexStringToBase64(DecryptTest3.java:38) at com.motorola.gst.DecryptTest3.main(DecryptTest3.java:16)

+0

看起来像它的[这]重复[1] [1]:http://stackoverflow.com/questions/7372268/how-to-convert-hex-to-base64 – banjara

回答

4
所有你必须指定(在你的案件16)指定基数的 parseByte方法,以避免NUMBERFORMAT异常

第一:

buffer[i/2] = Byte.parseByte(hexString.substring(i, 2),16); 

但是你的代码似乎打破,看看修正一个:

 if ((hexString.length()) % 2 > 0) 
      throw new NumberFormatException("Input string was not in a correct format."); 
     int[] buffer = new int[hexString.length()/2]; 
      int i = 2; 
      while (i < hexString.length()) 
      { 
       buffer[i/2] = Integer.parseInt(hexString.substring(i, i + 2),16); 
       i += 2; 
      } 

你的循环是错误的,你有,因为你有你的输入字符串中的某些值溢出字节能力,解析为整数...

如果您需要字节你可以施放解析的int字节这样:

 byte[] buffer = new byte[hexString.length()/2]; 
      int i = 2; 
      while (i < hexString.length()) 
      { 
       buffer[i/2] = (byte)Integer.parseInt(hexString.substring(i, i + 2),16); 
       i += 2; 
      } 
+0

感谢aleroot !这是非常有帮助 –

+0

@aleroot在你的第二个例子中,你不应该将我初始化为0而不是2吗? – Ben

0

发现了类似的解决方案,认为这可能是件好事莎尔e:

public static string convertHexToBase64String(String hexString) 
    { 
     string base64 = ""; 

     //--Important: remove "0x" groups from hexidecimal string-- 
     hexString = hexString.Replace("0x", ""); 

     byte[] buffer = new byte[hexString.Length/2]; 

     for (int i = 0; i < hexString.Length; i++) 
     { 
      try 
      { 
       buffer[i/2] = Convert.ToByte(Convert.ToInt32(hexString.Substring(i, 2), 16)); 
      } 
      catch (Exception ex) { } 
      i += 1; 
     } 

     base64 = Convert.ToBase64String(buffer); 

     return base64; 
    } 

希望它可以帮助别人。

相关问题