Nei*_*los 2 java binary bit-manipulation
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 = 13;
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]);
}
Run Code Online (Sandbox Code Playgroud)
我对此的期望是这个;
s0
二进制是 b0000_1111_1111_1111
s1
二进制是 b0000_0000_0000_1101
sh
然后成为 b1101_1111_1111_1111
见前1
是符号,其余15位给出了值,sh
十进制是-24575
但这不是我所得到的输出到控制台(这是-8193
).
我错了什么?
结果实际上是正确的.二进制数表示在所谓的2s补码中.因此,要计算负数的绝对值,您不仅要删除符号位并查看剩余的内容.而是这样做:1.翻转所有位,包括符号位2.添加1
在你的情况下,这意味着你得到
这是8193,这正是打印出来的.