I played with bitwise operations to compactly store information about objects, what I intend to do is to have short[][]
, which stores two pieces of information for each record, that is, the first set of bits (either 8 or 4) contains information, and the remaining remaining bits (8 or 12, respectively) store the rest.
In the code below, I demonstrate two examples that I talked about, the following questions:
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 problem is that in test2 () I expected I could only use signed values, however I seem to be able to use 4095 values ββfor 12 bits and 15 for 4 bits (I expected ranges to be From - 2048 to 2047 and from -8 to 7), how does it work with these values, what am I missing?
Another problem: why can't I use 1011111100110111
in test1 ()?
Finally, is it a good idea to store information this way? The array will be approximately 500x200 or 1000x500 something like this.
source share