Java - read bytes at a given offset

I am having a little trouble understanding how I can read and return the value of a specific offset position in a file.

For example, from my hex editor, I know the offset is D768 and the value is 32 bits. So how can this value be read and displayed in the label.

Any help would be generally appreciated.


source to share

4 answers

I think is your new friend :-)

Beware of the following code, it hasn't been tested.

RandomAccessFile raf = new RandomAccessFile("foo.bin", "r");;
int value =;




Use the DataInputStream class. Open the file and place it with skipBytes(offset)

and then call readInt()

. This will give you 32 bits, starting at the offset you are using.

(Note that this assumes the integer is in the most significant byte file.)



Use skipBytes

to jump to a preset position. To read a 32 bit number, you can use DataInputStream

if value is big-endian. If it's a bit, you need to manually convert four bytes to int


int value = (int)bytes[0]
        | ((int)bytes[1] << 8)
        | ((int)bytes[2] << 16)
        | ((int)bytes[3] << 24);




Refuse to skip RandomAccessFile.skipBytes before offset, this class can help you.



All Articles