English 中文(简体)
Java - Bitwith 操作没有获得预期效果
原标题:Java - Bitwise operations not getting what expected
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]);

}

我所期望的就是这个;

二进制中的 s0 b0000_1111_1111_1111_1111

二进制中的 s1 b0000_0000_00_0000_00_11001

sh 然后成为 b1101_1111_1111_1111_1111_1111

先前的 1 是符号, 其余的 15 位数给出了数值, 所以小数点中的 sh 24575 , 但这不是我对控制台的输出( 这是 -8193 )。

我哪里错了?

最佳回答

The result is actually correct. Binary numbers are represents in what is called the 2s-complement. So to compute the absolute value of a negative number, you do not just remove the sign bit and see what remains. Rather you do this: 1. Flip all bits, including the sign bit 2. Add 1

在你的情况,这意味着你得到

  1. 0010_0000_0000_0000
  2. 0010_0000_0000_0001

也就是8193, 这正是打印出来的。

问题回答

b1101_1111_1111_1111 is -8193, 它正在输出正确的答案。 可能想要刷新您的 2 补充 。

http://en.wikipedia.org/wiki/ 2%%27s_complement

使用的表示法不是符号模量, 而是 2 共 。 因此, 为了知道哪个数字由从一个开始的位数序列代表, 您必须先减去一个位数, 然后反转。 在您的情况中, 您将得到 1101_ 1111_ 1111_ 111_ 1110 的反转, 这将给 010_ 00_ 00_ 0000_ 00_ 00_ 001 。 这会是8193 exacly 8193 。 因此, 没有任何问题 - 您只是混淆了nteral 代表机制 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签