Java 从ascii转换为十六进制并再次转换时丢失左引号
使用一些不同的Stackoverflow源代码,我用JAVA实现了一个相当简单的Base64到十六进制的转换。然而,由于一个问题,我测试了我的结果,尝试将我的十六进制代码转换回文本,以确认它是正确的,并发现索引11(左引号)处的字符在翻译过程中不知何故丢失了 为什么hexToASCII会转换除左引号以外的所有内容Java 从ascii转换为十六进制并再次转换时丢失左引号,java,hex,base64,ascii,Java,Hex,Base64,Ascii,使用一些不同的Stackoverflow源代码,我用JAVA实现了一个相当简单的Base64到十六进制的转换。然而,由于一个问题,我测试了我的结果,尝试将我的十六进制代码转换回文本,以确认它是正确的,并发现索引11(左引号)处的字符在翻译过程中不知何故丢失了 为什么hexToASCII会转换除左引号以外的所有内容 public static void main(String[] args){ System.out.println("Input string:"); Strin
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);
}
publicstaticvoidmain(字符串[]args){
System.out.println(“输入字符串:”);
字符串myString=“aaaaa qeafxux1iatiz8=”;
System.out.println(myString+“\n”);
//托阿西
字符串ascii=base64UrlDecode(myString);
System.out.println(“Base64到Ascii:\n”+Ascii);
//托赫克斯
字符串hex=toHex(ascii);
System.out.println(“Ascii到十六进制:\n”+Hex);
字符串back2Ascii=hexToASCII(十六进制);
System.out.println(“十六进制到Ascii:\n”+back2Ascii+“\n”);
}
公共静态字符串hexToASCII(字符串hex){
如果(十六进制长度()%2!=0){
System.err.println(“需要偶数个字符”);
返回null;
}
StringBuilder sb=新的StringBuilder();
//将十六进制0232343536AB转换为两个字符流。
对于(int i=0;i
返回:
它没有松动。它在默认字符集中无法理解。使用
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());
}
它没有松开它。它在默认字符集中无法理解。使用
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());
}
按照您指定的方式更改了它,这不会影响任何事情。谢谢。这消除了我的前导空白,但这不是问题。按照您的指定进行更改,这不会影响任何内容。谢谢。这消除了我领先的空白,但这不是问题。