java - 在十六进制和 ascii 之间转换时丢失字符

标签 java hex ascii

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/

相关文章:

java - 在整个项目中创建 List 时更改为编译器 1.7 会产生错误

c++ - 将 Hexdump 转换为 c 中的字符串

c - 在 C 中将十六进制数打印为十进制

java - 将数字添加到字符以使其成为另一个字符

python - 从 .txt 文件中删除 ASCII 编码的二进制 blob

java - 有没有办法将 String.format 传递给 thymeleaf 模板?

java - Spring MVC @ModelAttribute 不适用于用户定义的依赖项

java - 控制用于 MimeMessage 附件的 DataContentHandler?

c++ - 为什么是 0022FF08 + sizeof(int) = 0022FF0C 而不是 0022FF0A?

python - 如何将 ASCII 字节文件作为实际字节写入二进制文件?