Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);

}

What I expect from this is this;

s0 in binary is b0000_1111_1111_1111

s1 in binary is b0000_0000_0000_1101

sh then becomes b1101_1111_1111_1111

The preceeding 1 is the sign and the remaining 15 bits gives the value so sh in decimal is -24575 but this is not what I get outputted to the console (which is -8193).

What am I getting wrong?

like image 816
Neilos Avatar asked Nov 20 '25 17:11

Neilos


1 Answers

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

In your case that means you get

  1. 0010_0000_0000_0000
  2. 0010_0000_0000_0001

Which is 8193, which is exactly what is printed out.

like image 117
Jochen Avatar answered Nov 23 '25 08:11

Jochen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!