gpt4 book ai didi

java - 从 ASCII 转换为十六进制并再次转换回来时丢失左引号

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:14 24 4
gpt4 key购买 nike

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

最佳答案

它不会丢失。它无法理解您的默认字符集。请改用 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());
}

关于java - 从 ASCII 转换为十六进制并再次转换回来时丢失左引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10059785/

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