gpt4 book ai didi

java - 将十六进制字符串转换为 base64

转载 作者:行者123 更新时间:2023-12-04 05:28:58 24 4
gpt4 key购买 nike

请帮助我将十六进制字符串转换为 base64

这是我得到异常(exception)的地方

 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);

}

我在这里遇到一个异常(exception): 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)

最佳答案

首先,您必须在 parseByte 中指定指定基数(在您的情况下为 16)。避免 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;
}

关于java - 将十六进制字符串转换为 base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12870645/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com