包装2短裤成一个整型,处理消极和积极 [英] Packing two shorts into one int, dealing with negative and positive

查看:217
本文介绍了包装2短裤成一个整型,处理消极和积极的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的一类PackedUnsigned1616存储两个无符号短裤在一个int和存储两个有符号短裤在一个int类型的类PackedSigned1616。我读了关于位操作,但我仍然对如何处理与困惑签名和未签名,并且是短的范围或大或小的值(它们被传递两个整数)。下面是我到目前为止有:

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. 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). 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. 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;
    }
}

有关签署的价值观,我想你需要做的就是修改getLeft和GetRight时如下:

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
    }

这篇关于包装2短裤成一个整型,处理消极和积极的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆