views:

39

answers:

2

I'm trying to write a ROM file patcher and I came to this in the documentation:

The next three bytes are the place in the destination file
(the file to be patched) where a change is to be made.

The two bytes following that are the length of the amount
of data to be changed.

How would I turn those three and two bytes into a single number in java properly?

+2  A: 

Strangely, I see a valid answer by Joey, which he deleted 10 minutes ago:

(byte1 << 16) + (byte2 << 8) + byte3

The only thing I have to add: do not convert bytes you read from InputStream to byte type (InputStream#read returns int value between 0 and 255). That'll turn 255 in -1, for example, and we don't need such side-effect.

So, it could look like

(in.read() << 16) + (in.read() << 8) + in.read()
Nikita Rybak
+1  A: 

Make sure you use a descendent of InputStream (byte vs char input).

The most important question to ask is if the data is stored in "little-endian" or "big-endian" fashion. I'll assume little-endian (x86). For the three-byte number:

FileInputStream fs = new FileInputStream(...);

int byte1 = fs.read();
int byte2 = fs.read();
int byte3 = fs.read();
int data = (byte3 << 16) | (byte2 << 8) | byte1;

For little-endian, the first byte read is the least significant byte.

If you need big-endian, change the last line to:

int data = (byte1 << 16) | (byte2 << 8) | byte3;
RD
thank you, i think this'll work.
William