Unpacking three values packed into a Long

I have the following bitwise operation that generates a hash:

(z shl 28) or (y shl 14) or x // (z << 28 | y << 14 | x) in java

I want to be able to deduce x, y and z from the hash calculated above. I can get Z and X every time, but I’m having trouble getting Y – it only works occasionally.

Z will always be less than 4. And x and y will be no bigger than the max short value.

This is what I’m doing:

    val hash = 684297131L // sample hash
    val z = hash shr 28
    val y = hash shr 14 // this works only sometimes
    val x = hash and 0xfff

I think I’m missing something simple here, any help appreciated.

>Solution :

Your "hash" doesn’t look too much like a hash. It looks more like packing 3 fields into a long.

You can get x, y, and z that produce the same "hash" like this:

val z = hash shr 28
val y = (hash shr 14) and 0x3fff
val x = hash and 0x3fff

This may be exactly what you want. There are different numbers that could produce the same hash, but these are the simplest.

Leave a Reply