I'm trying to write a Chip8 emulator with java and I've come across a question with the readAllBytes
function in Java Files
. When I loaded the bytes from the ROM I'm using to test into the "memory" array of my emulator, I tried to print those bytes to see if they are going into the memory correctly. I used Integer.toHexString
to see those bytes as hex values and compare them to the actual file that I loaded with a hex editor, but the output that it gives me is strange:
First bytes of the file:
00 e0 a3 4c
Output from test:
0 ffffffe0 ffffffa3 4c
Code:
public void loadToMem(byte[] program) {
for(int i = 0; i < program.length; i++) {
this.memory[i+512] = program[i];
System.out.println(Integer.toHexString(this.memory[i+512]));
}
this.initializeComponents();
}
Those values are just an error in the representation that Integer.toHexString
gives and the values are being loaded correctly or are they really being loaded incorrectly? Why is it padding with f's?
byte
values in Java are signed 8-bit values. Becausee0
anda3
each have their high order bit is set (they have a value >=80
hex), they represent negative values. Then, when you pass them toInteger.toHexString
, the values are extended to 32-bit values. What you are seeing is the equivalent 32-bit hex representation of these negative 8-bit values. This is called Two's Complement representation, which is what is used most often to represent signed integer values in a computer's memory.With Two's Complement, a signed 8-bit (single byte) integer with hex value
e0
has the decimal value -32. A signed 32-bit integer representation of -32 decimal isffffffe0
in hex. When you extend a two's complement positive value to a wider representation, you pad with0
s. When you extend a negative twos complement value, you pad withff
values. This works the same way when extending a twos complement value to any number of bytes.Most of us probably agreed with you that this is "a bit strange" the first time we saw how negative integers are interpreted in a computer's memory.
Here's a link to a simpler explanation of Two's Complement