我正在创建一个PackedUnsigned1616类,它在一个int中存储两个unsigned short,以及一个PackedSigned1616类,它在一个int中存储两个带符号的short。我已经阅读了按位运算,但我仍然对如何处理有符号和无符号以及大于或小于short的范围(它们作为两个整数传入)的值感到困惑。这是我到目前为止所得到的:
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;
}
}
这整个概念让我很困惑,所以如果你能对它有所了解,那将会有很大的帮助。
答案 0 :(得分:8)
初始化LEFT和RIGHT的有趣方式。试试这个:
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;
}
}
对于签名值,我认为您需要做的就是修改getLeft和getRight,如下所示:
public int getLeft() {
return field >> 16; // sign bit is significant
}
public int getRight() {
return (short) (field & RIGHT); gets cast back to signed int
}