Reading hex data into a byte array in Java?

I am reading data from SNES ROM using Java. I open the stream and read 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 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 behaves strangely. After setting up some debug statements, I have this template 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 the data appears, but I noticed incorrect values โ€‹โ€‹elsewhere in the program.)

As far as I can tell, my Java byte array does not respect hexadecimal data. How can I set an array of bytes for this?

+4
source share
3 answers

Java treats all bytes as signed, so they can only be in the range from -128 to +127. The E4 bit diagram corresponds to -28 in two additions.

You can convert signed bytes to makeend-unsigned-int by doing something like String.valueOf(data[ref] & 0x00FF) . This will override the character bit and will automatically convert to int.

+8
source

Works great. Keep in mind that byte is a signed type, so a value greater than or equal to 128 is interpreted as 256 - value .

+1
source

Try using the function to print each byte in the better known zero-width format:

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

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

+1
source

All Articles