javabit-manipulationkeytab

Understanding why certain bit manipulation operations are performed


Below is the source code of Keytab implementation in Java. This snippet reads the key version from the keytab file. I am having trouble understanding how this works. Why is the bitwise AND and shift left operation performed?

What my code calls:

KeyTab keytab = KeyTab.getInstance(keytabFile); // passing keytab file location. 

This file is in binary format. KeyTabInputStream reads the data.

  private void load(KeyTabInputStream var1) throws IOException, RealmException {
        this.entries.clear();
        **this.kt_vno = var1.readVersion();**
        if (this.kt_vno == 1281) {
            var1.setNativeByteOrder();
        }

        boolean var2 = false;

        while(var1.available() > 0) {
            int var4 = var1.readEntryLength();
            KeyTabEntry var3 = var1.readEntry(var4, this.kt_vno);
            if (DEBUG) {
                System.out.println(">>> KeyTab: load() entry length: " + var4 + "; type: " + (var3 != null ? var3.keyType : 0));
            }

            if (var3 != null) {
                this.entries.addElement(var3);
            }
        }

    }
    public int readVersion() throws IOException {
        int var1 = (this.read() & 255) << 8;
        return var1 | this.read() & 255;
    }

Solution

  • this.read() presumably returns 8 "interesting" bits since & 255 "retrieves" only the last 8 bits, shifting that by 8 bits means that now the bits 9-16 hold the data.
    Then performing another read + & again gets 8 bits, | that with the shifted bits from the step prior you now have one int with 16 relevant bits set: bit 1-8 hold the result of the second read while bits 9-16 hold the bits of the first read.