Double comparison trick in Java

C++ allows you to combine two integer comparisons in one for range checking, like

(unsigned)X < (unsigned)Upper

which returns true when

0 <= X < Upper

The Java language has no unsigned type. Do you see a way to obtain the same effect, using a single comparison and not too much overhead ?

Update :

From a comment by @Bathsheba, the char type is unsigned 16 bits and will be fit for my purpose, as my integers are actually in the range of shorts.

The question remains open for plain int s.

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


If you want a datatype in Java that is able to hold the range of values that an unsigned 32-bit int can hold, then you need long . You can bit-mask with 32 one-bits to convert the signed int that is possibly negative to a surely-positive long value.

(x & 0xffffffffL) < upper

//             ^
//             Implicit conversion to long (of both arguments)

Of course the 64-bit "and" and the 64-bit comparison will take some extra time but probably less than the pipe line breaks.

链接地址: http://www.djcxy.com/p/93560.html

上一篇: 第一个时代过度配合

下一篇: Java中的双重比较技巧