简体   繁体   English

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

[英]Program to read bytes from file and convert to 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) {
        }

    }
}

Output- 输出 -

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

The output is mostly correct. 输出大部分是正确的。 I can't figure out where these ffffffs are coming in my output. 我不知道这些ffffff在我的输出中的位置。 And also single single characters are missing their 0. eg. 并且单个单个字符也缺少其0。 d should be displayed as 0D d应显示为0D

input.readByte() returns a signed byte; input.readByte()返回一个有符号的字节; when the highest bit of that byte is 1, it is interpreted as a negative number, and Integer.toString sign-extends it to an int. 当该字节的最高位为1时,它将被解释为负数,并且Integer.toString将其符号扩展为一个int。

Instead of Integer.toString , use String.format("%02x", input.readByte() & 0xFF) , which will interpret the byte as unsigned and force exactly two hexadecimal digits to be used. 代替Integer.toString ,使用String.format("%02x", input.readByte() & 0xFF) ,它将解释该字节为无符号并强制使用两个十六进制数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM