How do I save multiple small integers in one integer via bitshifting?

隐身守侯 提交于 2019-12-06 09:45:48

If your numbers are in the range 0...255, this example will encode three numbers into one int and then decode it again...

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

(b1 & 0xFF) - Gets the first 8 bits of b1

((b2 & 0xFF) << 8) - Gets the first 8 bits of b2 and shifts them left 8 bits

((b3 & 0xFF) << 16) - Gets the first 8 bits of b3 and shifts them left 16 bits

These three numbers are ORed together.

If you have negative numbers or number more than 255, you'll get different results.

Given N, M and O and assuming N * M * O doesn't overflow, you can pack and unpack your indices like this:

int packed = o * (N * M) + m * N + n;
int o = packed / (N * M);
int m = (packed % (N * M)) / N;
int n = packed % N; // is equal to (packed % (N * M)) % N

If you want to use bit-shifting, make sure you chose N, M, O as powers of 2. Let's say N = 2^NS, M = 2^MS and O = 2^OS packing and unpacking would look like this:

int packed = (o << (NS + MS)) | (m << NS) | n;
int o = (packed >> (NS + MS)) & ((1 << OS) - 1);
int m = (packed >> NS) & ((1 << MS) - 1);
int n = packed & ((1 << NS) - 1);

All of the above assume n=0..N-1, m=0..M-1 and o=0..O-1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!