1

In java, Integer is 32bit and Short is 16bit.

I was trying to combine 2 Short into a signle Integer, and want to restore them some time.
one Short value stores at the higher 16bit, and another stored at the lower 16bit.

For example, I want 2 Short value (99, 100) be stored in one Integer x, and extract them out sometime.

At first I tried the bit operation (<< 16), but cannot restore the two numbers.

Wangwang
  • 159
  • 1
  • 15

2 Answers2

3

If the values can be negative, it takes a little more effort to deal with the sign of the low half:

int combined = (high << 16) | (low & 0xFFFF);

No casts are needed, they happen implicitly. But the & 0xFFFF part is necessarily to avoid overwriting the high half with ones if low is negative.

Split is still equally simple like this:

short high = (short)(combined >> 16);
short low = (short)combined;
harold
  • 61,398
  • 6
  • 86
  • 164
0

You can split the first and second half of 16 bit to store the short values in a int. And then extract the shorts from that int to two short. Here is an example:

public class ShotToInt {

  public static void main(String[] args) {
    short x, y;
    x = 101;
    y = 500;

    // creating the int by storing x in first half and y in last half.
    int xy = ((int) x << 16) | y;

    System.out.println("x=" + x + " y=" + y);
    System.out.println("in bit: " + Integer.toBinaryString(x) + ":" + Integer.toBinaryString(y));
    System.out.println("in bit: " + Integer.toBinaryString(xy));

    // shifting bits to 16 digit to restore the x
    short xx = (short) (xy >> 16);
    // directly casting to short to extract y
    short yy = (short) xy;

    System.out.println("x=" + xx + " y=" + yy);
    System.out.println("in bit: " + Integer.toBinaryString(xx) + ":" + Integer.toBinaryString(y));
    assert x == xx;
    assert y == yy;
  }

}
MD Ruhul Amin
  • 4,386
  • 1
  • 22
  • 37