3

I'm trying to understand some basics, I'm trying to read binary file using Java, in this case this is irrelevant, but might help with the approach, I think. So, I know that the first four bytes of the file have a value of 0x9AA2D903. But, when I read it they have "reversed" order, like that: 03 D9 A2 9A (03 - the first byte, D9 - the second and so on).

What I need to do in order to compare the value of 0x9AA2D903 and the output I'm getting? First, that comes in mind is to get an array of these 4 bytes, then flip them and convert to string. But it looks horrible.

If you could point to some literature, that would be great.

code:

Path path = Paths.get(Utils.getResourseURI("Demo.kdbx"));

try {
    FileInputStream fin = new FileInputStream(path.toString());
           }
    int len;
    byte bytes[] = new byte[16];

    do {
        len = fin.read(bytes);
        for (int j = 0; j < len; j++)
            System.out.printf("%02d\n", bytes[j]);

    } while (len != -1);
}
Sébastien
  • 893
  • 2
  • 9
  • 13

2 Answers2

3

I can't post comments, but you should take a look at this SO post.

It looks like your file is a different Endian than what you're reading with. E.g. file might be Little Endian while you're reading with Big Endian. So instead of trying to compare values and then reverse the order, it would be better to just read it in the desired Endian.

Community
  • 1
  • 1
far
  • 129
  • 8
1

The problem you are having is with Endian-ness of the source data

http://betterexplained.com/articles/understanding-big-and-little-endian-byte-order/

Some systems write binary data in reverse order and this must be handled in anything reading binary data.

UNIX and networks use Big Endian.

The Intel x86 and x86-64 series of processors use the Little Endian format

This SO answer explains how you can read it: https://stackoverflow.com/a/3438744/5672880

Community
  • 1
  • 1
John Scattergood
  • 1,032
  • 8
  • 15