Neilos
Neilos

Reputation: 2746

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?

Upvotes: 2

Views: 193

Answers (3)

Jochen
Jochen

Reputation: 2295

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.

Upvotes: 6

rlinden
rlinden

Reputation: 2041

The representation used is not sign-modulus, but yet 2-complement. Therefore, in order to know which number is represented by a sequence of bits that starts with one, you must subtract 1 and then invert. In your case you will get 1101_1111_1111_1110 inverted which will give 0010_0000_0000_0001 which is exatcly 8193. Therefore, there is no problem whatsoever - you just confused the nternal representation mechanism.

Upvotes: 2

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26078

b1101_1111_1111_1111 is -8193, it is outputting the correct answer. Might want to brush up on your 2s complements.

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

Upvotes: 6

Related Questions