import java.lang.*;
public class asciiHex{
public static void main(String args[]){
String ascii1 = "e v e r y s e c o n d c h a r";
String hex = "";
String ascii2 = "";
char[] chars = ascii1.toCharArray();
for(int i = 0; i < ascii1.length(); i++){
hex += (Integer.toHexString( (int)chars[i]));
}
System.out.println(ascii1);
System.out.println(hex);
for(int i = 0; i < hex.length(); i+=2){
String temp = hex.substring(i, i+=2);
ascii2 += ((char)Integer.parseInt(temp, 16));
}
System.out.println(ascii2);
}
}
这是我的代码。它应该接受一个字符串并将其从 ascii 转换为十六进制,然后再返回。当我运行该程序时,它以某种方式丢失了每一秒的字符。我很确定我使用子字符串的方式有问题,但我不明白为什么会这样。
谢谢。
最佳答案
您将计数器 (i
) 递增两次,这就是它每隔一个字符跳过一次的原因:
for(int i = 0; i < hex.length(); i+=2){ // <-- first increment
String temp = hex.substring(i, i+=2); // <-- second increment
ascii2 += ((char)Integer.parseInt(temp, 16));
}
应该是:
for(int i = 0; i < hex.length(); i+=2) { // <-- increment here
String temp = hex.substring(i, i+2); // <-- do not increment here
ascii2 += ((char)Integer.parseInt(temp, 16));
}
关于java - 在十六进制和 ascii 之间转换时丢失字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35123229/