Neilos
Neilos

Reputation: 2746

Java - Bitwise operations confusing me, it works but I thought it shouldn't

I have been playing with bitwise operations in order to compactly store information about objects, what I intend to do is have a short[][] that stores two pieces of information per entry, that is that the first set of bits (either 8 or 4) contains info and then the remaining bits (either 8 or 12 respectively) store the rest.

In the code below I demonstrate the two examples I mentioned, questions to follow;

private void test1() {
    // This test takes a 16 bit binary number and breaks it into two
    // bytes of 8 bits. It then takes the bytes and sticks them back
    // together then outputs their decimal value
    String st = "0011111100110111";
    short s = Short.parseShort(st,2);
    byte[] ba = new byte[] {
        (byte)(s & 0xFF),
        (byte)((s >>> 8) & 0xFF)
        };

    System.out.println(s);
    System.out.println(ba[0]);
    System.out.println(ba[1]);

    byte b0 = ba[0];
    byte b1 = ba[1];

    short sh = (short)((b1 << 8) | b0);

    System.out.println(sh);
}

private void test2() {
    // This test takes two shorts and sticks them together in a
    // 4 bit 12 bit configuration within a short, it then breaks
    // them apart again to see if it worked!
    short s0 = 4095;
    short s1 = 15;

    short sh = (short)((s1 << 12) | s0);

    System.out.println(sh);

    short[] sa = new short[] {
        (short)(sh & 0xFFF),
        (short)((sh >>> 12) & 0xF)
    };

    System.out.println(sa[0]);
    System.out.println(sa[1]);

}

My main concern is that in test2() I expected to only be able to use signed values, however I seem to be able to use the values 4095 for the 12 bit and 15 for the 4 bit (I expected ranges to be -2048 to 2047 and -8 to 7), how come it works with these values, what am I missing?

Also another concern, why can't I use 1011111100110111 in test1()?

Lastly, is this a good idea to store information in this manner? The array will be approx 500x200 or 1000x 500 something like that.

Upvotes: 4

Views: 261

Answers (1)

Tim
Tim

Reputation: 35933

The reason why 4095 works in the second line, is because you are sign extending it before printing it. If you understand that unsigned 4095 is exactly the same bits as -2048, it just matters how you interpret them.

If you were printing out a 12-bit signed value, it would be this: 'b1111_1111_1111, which would be interpreted as -2048. However you're casting this to a short which adds another 4 bits at the end: 'b0000_1111_1111_1111. 4095 fits fine inside this value.

The same applies to 15/-8, you're casting it to a larger value before printing.

Upvotes: 4

Related Questions