Problem
I wanted to perform bit operation with Java and was expecting the same behavior that happens with C or C . However it is not working as intended.
In C or C
printf("%d", 0 > 0xFFFFFFFF);
this would return 0
(which is false)
However in Java
System.out.println(0 > 0xFFFFFFFF);
returns true
What I understand
I know how 2's complement works. The below is that I am guessing what is happening internally with those two languages.
- C or C just translates
0xFFFFFFFF
to0xFFFFFFFF
itself, so value0
is smaller than0xFFFFFFFF
thus resultingfalse
. - Java translates
0xFFFFFFFF
with 2's complement as-1
, so value0
is bigger than-1
thus resultingtrue
.
Question
Is there any possible way that Java can work just like C or C did? I would like Java's hex values to be recognized as hex values instead of converting them into signed int values?
CodePudding user response:
In Java the literal 0xFFFFFFFF
represents the int
whose value is -1. In Java int
is a signed type.
In C / C 0xFFFFFFFF
will typically be either a long
or an unsigned long
. In the former case, it represents -1. In the latter case it represents 2^32 - 1 ... a very large positive integer.
Is there any possible way that Java can work just like C or C did?
No.
I would like Java's hex values to be recognized as hex values instead of converting them into signed int values?
Well the problem is that Java int
is signed. And you can't change that.
However, there are methods in the Integer
class that will treat an int
value as if it was unsigned; e.g. Integer.compareUnsigned
, divideUnsigned
and parseUnsignedInt
. See the javadocs for more details.