Packing two shorts in one int dealing with negative and positive

I am making a PackedUnsigned1616 class that stores two unsigned shorts in one int and a PackedSigned1616 class that stores two signed shorts in one int. I read bitwise operations, but I'm still confused about how to work with signed and unsigned values ​​that are more or less than a short range (they are passed as two ints). Here is what I have so far:

public final class PackedUnsigned1616 { public final int field; private static final int RIGHT = (2 << 15) - 1; private static final int LEFT = ((2 << 31) - 1) ^ RIGHT; public PackedUnsigned1616(int left, int right) { field = (left << 15) | (right & RIGHT); } public int getLeft() { return field >> 15; } public int getRight() { return field & RIGHT; } 

}

This whole concept is confusing to me, so if you could shed some light on it, it would help a lot.

+6
source share
1 answer

An interesting way to initialize LEFT and RIGHT. Try instead:

 public final class PackedUnsigned1616 { public final int field; private static final int RIGHT = 0xFFFF; public PackedUnsigned1616(int left, int right) { field = (left << 16) | (right & RIGHT); } public int getLeft() { return field >>> 16; // >>> operator 0-fills from left } public int getRight() { return field & RIGHT; } } 

For signed values, I think all you have to do is change getLeft and getRight as follows:

  public int getLeft() { return field >> 16; // sign bit is significant } public int getRight() { return (short) (field & RIGHT); gets cast back to signed int } 
+8
source

Source: https://habr.com/ru/post/887574/


All Articles