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

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.

+4
source share
1 answer

The reason 4095 works on the second line is because you sign it before printing it. If you understand that unsigned 4095 are exactly the same bits as -2048, it is simply important how you interpret them.

If you were printing a 12-bit signed value, it would be like this: 'b1111_1111_1111 , which would be interpreted as -2048. However, you drop this to a short one that adds another 4 bits at the end: 'b0000_1111_1111_1111 . 4095 is great for this value.

The same goes for 15 / -8, before you print, you give it more importance.

+4
source

Source: https://habr.com/ru/post/1414206/


All Articles