1
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. And also single single characters are missing their 0. eg. d should be displayed as 0D

1 Answer 1

2

input.readByte() returns a signed byte; 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.

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.