java - 程序从文件读取字节并转换为十六进制

标签 java io hex

import java.io.*;

public class foo {

    public static void main(String[] args) {

        try {
            DataInputStream input = new DataInputStream(new FileInputStream(
                    "data.dat"));

            while (input.available() > 0) {

                String hex = Integer.toHexString(input.readByte()); //I think this is where the problem is

                System.out.print(hex + ' ');

            }

        } catch (IOException e) {
        }

    }
}

输出-

ffffff89 50 4e 47 d a 1a a 0 0 0 d 49 48 44 52 0 0 0... (continues)

输出大部分是正确的。我无法弄清楚这些 ffffffs 在我的输出中来自哪里。而且单个字符也缺少 0。例如。 d 应显示为 0D

最佳答案

input.readByte() 返回一个有符号字节;当该字节的最高位为 1 时,它被解释为负数,并且 Integer.toString 将其符号扩展为 int。

使用String.format("%02x", input.readByte() & 0xFF)代替Integer.toString,它将把字节解释为无符号并且强制使用恰好两个十六进制数字。

关于java - 程序从文件读取字节并转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909273/

相关文章:

java - c 中的 JSTL 请求属性 :if

java - 如何将 Writer 转换为字符串

c - 文件 IO 性能 C

c++ - unsigned int有效位数

javascript - 函数中的这一行有什么作用?

java.sql.SQLException : The result set is closed on Firebird when executing two statements

Java 8 : CMS does not kick on for old generation even though CMSInitiatingOccupancyFraction specified

java - 在 Android 上将 SQL glob 样式模式转换为正则表达式的最佳方法是什么

创建一个大小为一页的文件并用\0 字节填充

qt - 如何将 Qcolor 值转换为十六进制值?