Packing two shorts into one int, dealing with negative and positive

心已入冬 提交于 2019-12-03 13:50:35

Interesting way to initialize LEFT and RIGHT. Try this 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 need to do is modify 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
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!