Question

I have a long value identifying invalid input and it should include 0s in upper 40 bits. So everytime I get a new input I've to compare it's upper 40 bits to verify if those are 0's to make sure it isn't invalid.

long invalid_id = 0;
long input ; //some input 

if ((input << 24) == id) {
   // invalid
}

Will this be sufficient?

Was it helpful?

Solution

You want to be using the right shift operators (there are two) and shift thevalue right:

if ((input >>> 24) == 0) {
    // high-order 40 bits are all 0.
}

Alternatively, you can simply bit-mask with:

if ((input & 0xFFFFFFFFFF000000L) == 0) {
    // high-order 40 bits are all 0.
}

Note that >>> will put 0 in the high-order bits, and >> will put 0 for positive numbers, and 1 for negative.

OTHER TIPS

If you want to check the top 40 bits are the same in two long values

long a, b;
if (((a ^ b) >>> 24) == 0) // top 40 bits are the same.

or

if (((a ^ b) & 0xFFFFFFFFFF00000000L) == 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top