5

I'm reading data from an SNES ROM using Java. I am opening a stream and reading in the bytes into an array:

InputStream stream = open("foo.rom");
final int startingSize = stream.available();
byte[] data = new byte[startingSize];
final int numberRead = stream.read(data, 0, startingSize);

In the ROM, I have this value:

E4 2B 00 02 03 00 FF 3A 00 83

228 43 0 2 3 0 255 58 0 131 (in decimal)

However, my code is behaving weirdly. After setting up some debug statements, I have this pattern when printing with String.valueOf(data[ref]):

-28 43 0 2 3 0 -1 58 0 -125

(This address in the ROM is the first where data appears, but I am noticing incorrect values elsewhere in the program.)

As near as I can tell my Java byte array is not respecting the hexadecimal data. How can I set my byte array to do so?

1
  • There is a specific warning in the Javadoc against using available() in exactly the way you're using it here. Commented Oct 12, 2017 at 9:16

3 Answers 3

7

Java treats all bytes as being signed, so they can only be in the range -128 to +127. The bit pattern E4 corresponds to -28 in two's complement.

You can convert signed bytes to pretend-unsigned-ints by doing something like String.valueOf(data[ref] & 0x00FF). That will strip off the sign bit and auto-convert to an int.

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

2 Comments

But then what am I to do? Replace the references of "byte" with "int," convert the data, and hope for the best?
No, only do the conversion for debugging. You probably want to keep the raw data as it is for the rest of your code.
2

Try using a function to print out each byte in the more well-known zero-padded hex string format:

public static String toHexString(byte b) {
    return String.format("%02X", b);
}

(Yes I know there are more efficient ways to write this method.)

Comments

1

It's working perfectly fine. Keep in mind that byte is a signed type, so a value greater or equal than 128 is interpreted as 256 - value.

1 Comment

No it isn't. It is interpreted as value-256.

Your Answer

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