DataInputStream readByte is returning a big value

310 views Asked by At

I'm creating a Chip-8 emulator that requires you to read virtual rom files in bytes. I have this code that is calling a readByte method. If you look at the values that this is printing out, some of them are regular bytes, and some of them are crazy big.enter image description here

1

There are 1 answers

1
Alex Shesterov On BEST ANSWER

DataInputStream.readByte() returns a byte which is a signed type. The returned value can be negative.

Integer.toHexString(intValue) returns a hex-representation of the value interpreted as an unsigned integer.

Thus, positive values (like 76, 12) are printed as you expect, while negative values are printed in two's complement representation (the way negative values are represented in Java).

For example, the printed value of fffffffe is a 32-bit (integer size) two's complement representation of -2.


To properly print byte values, use this:

System.out.println(String.format("%02x", tmp));

Note that this will also properly left-pad printed values with zeros.