Question

I'm doing an assignment using Java, and our lecturers provided an example code for us. I'm unable to understand some of the code so can anyone explain?

    private long magic;
    private int minor;

    magic = file.readUnsignedShort() << 16 | file.readUnsignedShort();
    mnior = file.readUnsignedShort();

I don't understand why did he use "readUnsignedShort" for both of them and why did he add "<< 16 | file.readUnsignedShort()" for magic. Any help will be much appreciated

Was it helpful?

Solution

A short uses 16 bits, an int uses 32 and a long uses 64 bits. Given this, there are not unsigned values in Java, so if the most significant bit is 1, it means the value is negative.

Splitting the code you have:

file.readUnsignedShort() <- reads 16 bits

<< 16 <- moves them 16 positions "to the left", adding zeros (it's like multiply by 2^16)

| file.readUnsignedShort(); <- in those 16 zeros, puts the next 16 bites read, using the OR operation, which works as follows:

xxxx0000 | 0000YYYY = xxxxYYYY

OTHER TIPS

Okay, let's start at the beginning.

  1. RandomAccessFile.readUnsignedShort() reads 16 bits of information from the file, without interpreting it as a 2s complement representation.
  2. So in the first line you do this: <first two bytes of the file> << 16 | <third and fourth bytes of the file>
  3. <<16 means shift the number left by 16 bits. For unsigned numbers, this is the equivalent of multiplying by 65536.
  4. | means do a bitwise or. Because we know the first number was shifted, in our case this is equivalent to just adding the numbers.

So this is what it does, why it does it is anybody's guess. You should ask your teacher really, but my guess is that it might have something to do with the fact that this is the only way to read a 32-bit unsigned number via RandomAccessFile.

This operation is like concat for bits.

short is 16 bit and integer is 32 bit long. Concatenating 2 short you will obtain a integer.

The << Operator stands for bitshift, in this way you are shifting the bits by sixteen positions.

Example:

NUMBER1 1111 1111 1111 1111
NUMBER2 0000 0000 0000 0000

NUMBER1 << 16 | NUMBER2 = 1111 1111 1111 1111  0000 0000 0000 0000

(thanks for hints)

magic = file.readUnsignedShort() << 16 | file.readUnsignedShort();

<< is bit shift operation

| is bitwise operation.

Read more here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top