Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ints.

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

like image 812
Yves Daoust Avatar asked Oct 11 '16 07:10

Yves Daoust


People also ask

Can you use == for doubles in Java?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

Does compareTo () work with doubles Java?

compareTo() is a built-in method in java that compares two Double objects numerically.

What is the use of == in Java?

In java both == and equals() method is used to check the equality of two variables or objects. == is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality.


Video Answer


1 Answers

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.

like image 173
Erwin Bolwidt Avatar answered Oct 07 '22 17:10

Erwin Bolwidt