Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding a set of three integers to one unique number

Tags:

java

So, my problem set is very simple. I am working with a set of three integers randomly selected from [0-65535] and my Job is to encode this integers into one unique number. Here is what I have tried so far

I have written a java function called pack to try and encode this numbers as follows

 private long pack(long a, long b, long c) {
        int N = 65535, M = 65536;
        return (a + (b * N) + c * N * M);
    }

And I have also written another java function to unpack or decode the packed number back to the original integers as follows

private long[] unpack(long packed) {
    int N = 65535, M = 65536;
    long a = (packed % N);
    long b = (packed / N) % M;
    long c = (packed % (N * M));
    return new long[]{a, b, c};
}

Now when I ran the code above in my main function using sample data {67, 8192, 7168} I am getting the following as result in my console output

Packing 67, 8192, 7168
Result=30786392678467

UnPacking 30786392678467
Result=[67, 8192, 57411]

From the above, clearly my first and second values are always correct but the last value always appear to be wrong. What am I possibly missing out.Your help is greatly appreciated. Thanks alot.

like image 632
mekings Avatar asked Jan 26 '23 16:01

mekings


1 Answers

I'm going to give you an alternative solution now, and then I can try to debug your current solution when I'm on a PC instead of a phone (rgettman beat me!).

Because each of the three numbers can be a maximum of 65535, that means that each number will fit into 16 bits. For that reason, you can simply build a unique long with the following:

long encoded = (a << 32L) | (b << 16) | c;

And decoding it would look like the following:

long a = (encoded >> 32) & 0xFFFFL;
long b = (encoded >> 16) & 0xFFFFL;
long c = encoded & 0xFFFFL;
like image 189
Jacob G. Avatar answered Jan 31 '23 19:01

Jacob G.