我一直以紧凑存储有关对象的信息玩弄位操作,我打算做的是有一个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]);
}
我主要关注的是,在测试2()我预计只有能够使用符号的值,但是我似乎能够使用的值4095的4位(我在12位和15预计范围为-2048至2047和-8至7),它是如何与这些值一起工作的,我错过了什么?
而且另一个问题,为什么我不能在测试1使用1011111100110111
()?
最后,以这种方式存储信息是一个好主意吗?该阵列将是约500x200或1000x 500类似的东西。
哈啊,当然,所述计算机不关心字节的整数值,直到它被解释(即输出),所有的时间之前,它仅仅是一个的1和0的串。天才,我完全错过了。 – Neilos