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