如何通过移位将多个小整数保存在一个整数中?

gui*_*unk 2 java arrays return return-type bit-shift

我在int[][][]数组中工作,我需要从静态函数返回该数组一个字段的地址。鉴于Array的维数将保持较小(int[32][32][32]),因此我想到了返回一个包含所有三个Values的数字,而不是使用包含这三个数字的Array。

我已经有了一个可行的解决方案,在该解决方案中,我将我的电话号码打包成一个字符串,然后通过接收方法将其解压缩Integer.parseInt(String)。不幸的是,这在运行时方面并不太好,所以我想到了移位。

我为我的英语不好而道歉,并希望这个简单的问题值得您耐心等待:)

Bre*_*etC 5

如果您的数字在0 ... 255范围内,此示例会将三个数字编码为一个int,然后再次对其进行解码...

public class BitDemo {

    public static void main(String[] args) {
        int encoded = encode(20, 255, 10);
        int[] decoded = decode(encoded);

        System.out.println(Arrays.toString(decoded));
    }

    private static int[] decode(int encoded) {
        return new int[] {
                encoded & 0xFF,
                (encoded >> 8) & 0xFF,
                (encoded >> 16) & 0xFF
        };
    }

    private static int encode(int b1, int b2, int b3) {
        return (b1 & 0xFF) | ((b2 & 0xFF) << 8) | ((b3 & 0xFF) << 16);
    }
}
Run Code Online (Sandbox Code Playgroud)

(b1 & 0xFF) -获取b1的前8位

((b2 & 0xFF) << 8) -获取b2的前8位并将其左移8位

((b3 & 0xFF) << 16) -获取b3的前8位并将其左移16位

这三个数字或运算在一起。

如果负数或数字大于255,则会得到不同的结果。