How to output the absolute value of unsigned integers in java

I want to assign 4294967295 variable ( 2^32-1 ) Obviously, I cannot do this with Integer and do it with Long .

However, I noted that Java 8 offers Unsigned Integer (at least some methods).

Does anyone know what the Integer.parseUnsignedInt() method Integer.parseUnsignedInt() ? When I enter "4294967295" to this and print the variable, it gives the result as -1 ( -2 for 4294967294 , -3 for 4294967293 , etc.)

Is there a way that I can still have 4294967295 in a variable?

Did I miss something?

 a=Integer.parseUnsignedInt("4294967295"); System.out.println(a); 

This gives a result as -1 , but I was expecting 4294967295 .

+8
java java-8 int unsigned
source share
3 answers

You can view this integer as an unsigned int by calling toUnsignedString() :

 int uint = Integer.parseUnsignedInt("4294967295"); System.out.println(Integer.toUnsignedString(uint)); 

You can also call some other methods that interpret this int as unsigned.

For example:

 long l = Integer.toUnsignedLong(uint); System.out.println(l); // will print 4294967295 int x = Integer.parseUnsignedInt("4294967295"); int y = 5; int cmp1 = Integer.compareUnsigned(x,y); // interprets x as 4294967295 (x>y) int cmp2 = Integer.compare(x,y); // interprets x as -1 (x<y) 
+17
source share

As far as I understand https://blogs.oracle.com/darcy/entry/unsigned_api , unsigned support is not performed by introducing a new type. The values ​​are still stored in the (signed) int variables, but they provide methods for interpreting the value as unsigned:

To avoid boxed overhead problems and allow reuse of built-in arithmetic operators, unsigned API support does not introduce new types, such as UnsignedInt, with instance methods for performing addition, subtraction, etc. However, this drawback of unsigned unsigned types at the Java level means that the programmer may accidentally incorrectly mix signed and unsigned values.

You used the "unsigned" version of the parsing, but you do not show which method you use to "print the variable." You probably chose (default) signed.

+2
source share

Is there a way that I can still have 4294967295 in varible?

Yes. Use long . (To me, it sounds like you overdid it.)

0
source share

All Articles