我一直在玩按位操作以便紧凑地存储有关对象的信息,我打算做的是有一个short [] [],每个条目存储两条信息,即第一组位(8或者4)包含信息,然后剩余的比特(分别为8或12)存储其余的.
在下面的代码中,我演示了我提到的两个例子,要遵循的问题;
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]);
}
我主要担心的是在test2()中我希望只能使用有符号值,但是我似乎能够使用4095的值为12位,15位为4位(我预期的范围是-2048到2047和-8到7),它是如何运用这些价值观的,我错过了什么?
另外还有一个问题,为什么我不能在test1()中使用1011111100110111?
最后,以这种方式存储信息是一个好主意吗?阵列将是大约500×200或1000x 500之类的东西.