Trouble understanding bitmasking

Recently I started trying to teach myself bitmasking, and I haven’t had much success. In my current game, I am trying to pack multiple variables of data type short into a single long. In addition to getting the below code to function properly, I had a few questions:

  • I have heard that primitive types in Java reserve the last bit to the sign of the variable (plus or minus). Is this true?
  • Java shorts are 2 Bytes, and longs are 8 Bytes. Should I then in theory be able to pack 4 shorts into 1 long? Will the different data types cause problems?

Below are my broken methods for packing/unpacking the shorts. I have an understanding of the bitwise operators and thier functions (although I’m a bit fuzzy on the difference between >> and >>>), so it’s more of the actual implementation that is confusing me.
Here is my packing method (components[] is guaranteed to be of length SHORTS_IN_PACK):

private static final long packShorts(short[] components) {
		//should initialize pack to all zero bits
		long pack = Long.MIN_VALUE;

		for (int i=0; i < SHORTS_IN_PACK; i++)
			pack |= (components[i] & 0xFFFF) << (i*16);

		return pack;
}

And here is my unpacking method:

private static final short[] unpackShorts(long pack) {
		short[] components = new short[SHORTS_IN_PACK];
		
		for (int i=0; i < SHORTS_IN_PACK; i++)
			components[i] = (short) (( pack >>> (i*16) ) & 0xFFFF); 

		return components;
}

Any advice would be helpful, especially if worded as simply as possible.
Thank you :slight_smile: