Home > other >  How to use hex as hex values in Java
How to use hex as hex values in Java

Time:03-07

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 to 0xFFFFFFFF itself, so value 0 is smaller than 0xFFFFFFFF thus resulting false.
  • Java translates 0xFFFFFFFF with 2's complement as -1, so value 0 is bigger than -1 thus resulting true.

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.

  • Related