Double Comparative Trick in Java

C ++ allows you to combine two integer comparisons in one to test a range, e.g.

(unsigned)X < (unsigned)Upper 

which returns true when

 0 <= X < Upper 

The Java language does not have an unsigned type. Do you see a way to get the same effect using one comparison and not too much overhead?

Update

From a comment by @Bathsheba, the char type is not 16 bit and would be suitable for my purpose, since my integers are really in the short range.

The question remains open for simple int s.

Perhaps something in the string (X | (Upper - 1 - X)) >= 0 , which allows a range of 30 bits.

+7
java comparison
source share
1 answer

If you need a data type in Java that can hold a range of values ​​that can hold an unsigned 32-bit int, you need long . You can use a 32-bit bitmask to convert a signed int, which is possibly negative, to a reliably positive long value.

 (x & 0xffffffffL) < upper // ^ // Implicit conversion to long (of both arguments) 

Of course, a 64-bit comparison of "and" and "64-bit" will take some extra time, but probably less than breaking a pipeline line.

+4
source share

All Articles