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.
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.
compareTo() is a built-in method in java that compares two Double objects numerically.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With