简体   繁体   English

将两条短裤打包成一个整数,处理负面和正面

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

I'm making a class PackedUnsigned1616 which stores two unsigned shorts in one int, and a class PackedSigned1616 which stores two signed shorts in one int. 我正在创建一个PackedUnsigned1616类,它在一个int中存储两个unsigned short,以及一个PackedSigned1616类,它在一个int中存储两个签名的short。 I've read up on bitwise operations, but I'm still confused on how to deal with signed and unsigned and values that are larger or smaller that a short's range (they are passed in as two ints). 我已经阅读了按位运算,但我仍然对如何处理有符号和无符号以及大于或小于short的范围(它们作为两个整数传入)的值感到困惑。 Here's what I've got 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 me a lot, so if you could shed a little light on it, that would help tremendously. 整个概念让我很困惑,所以如果你能对它有所了解,那将会有很大的帮助。

Interesting way to initialize LEFT and RIGHT. 初始化LEFT和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: 对于签名值,我认为您需要做的就是修改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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM