Java位操作让我困惑,它可以工作,但我认为它不应该';T
我一直在玩逐位操作,以便紧凑地存储有关对象的信息,我打算做的是使用一个Java位操作让我困惑,它可以工作,但我认为它不应该';T,java,bit-manipulation,Java,Bit Manipulation,我一直在玩逐位操作,以便紧凑地存储有关对象的信息,我打算做的是使用一个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
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]);
}
private void test1(){
//此测试获取一个16位二进制数,并将其拆分为两个
//8位的字节。然后,它将这些字节放回原处
//然后一起输出它们的十进制值
字符串st=“0011111100110111”;
short s=short.parseShort(st,2);
字节[]ba=新字节[]{
(字节)(s&0xFF),
(字节)((s>>>8)和0xFF)
};
系统输出打印项次;
System.out.println(ba[0]);
System.out.println(ba[1]);
字节b0=ba[0];
字节b1=ba[1];
短sh=(短)((b1>12)和0xF)
};
System.out.println(sa[0]);
System.out.println(sa[1]);
}
我主要关心的是,在test2()中,我希望只能使用有符号的值,但是我似乎能够使用值4095表示12位,使用值15表示4位(我希望范围为-2048到2047和-8到7),它如何与这些值一起工作,我缺少什么
还有一个问题,为什么我不能在test1()中使用1011111100110111
最后,以这种方式存储信息是一个好主意吗?数组大约为500x200或1000x500,类似于此。第二行之所以使用4095,是因为您在打印它之前要对其进行扩展。如果您知道无符号4095与-2048完全相同,那么如何解释它们就很重要了 如果您打印出一个12位有符号值,它将是这样的:
'b1111\u 1111\u 1111
,它将被解释为-2048。但是,您要将其转换为一个短字符,在结尾处添加另外4位:'b0000\u 1111\u 1111\u 1111
。4095在该值内非常适合
这同样适用于15/-8,在打印之前将其强制转换为更大的值 当然,在解释(即输出)之前,计算机并不关心字节的整数值,在此之前,它只是一个由1和0组成的字符串。天才,我完全错过了。