2012-05-24 62 views
4

我一直以紧凑存储有关对象的信息玩弄位操作,我打算做的是有一个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类似的东西。

回答

4

之所以4095件作品在第二行,是因为你在打印之前延长它的标志。如果你明白无符号4095和-2048是完全一样的,那么你是如何解释它们的。

如果打印出12位有符号数,这将是这样的:'b1111_1111_1111,这将被解读为-2048。然而,你正在将它缩短为在最后增加4位:'b0000_1111_1111_1111。 4095符合这个价值。

这同样适用于15/-8,您打印前将其转换为更大的值。

+0

哈啊,当然,所述计算机不关心字节的整数值,直到它被解释(即输出),所有的时间之前,它仅仅是一个的1和0的串。天才,我完全错过了。 – Neilos

相关问题