如何在java中输出无符号整数的绝对值 [英] How to output the absolute value of an Unsigned integer in java
问题描述
我想将 4294967295
分配给变量( 2 ^ 32-1
)
它是很明显,我不能用 Integer
来做到这一点,并且可以用 Long
来做。
I want to assign 4294967295
to a variable (2^32-1
)
It is obvious that I can't do that with Integer
, and can do it with Long
.
但是,我注意到Java 8提供了无符号整数(至少有一些方法)。
However, I noted that Java 8 offers Unsigned Integers (at least some methods).
有没有人知道方法是什么, Integer.parseUnsignedInt()
呢?
当我输入4294967295
并打印变量时,它输出为 -1
( -2
> 4294967294
, -3
for 4294967293
依此类推......)
Does any one know what the method, Integer.parseUnsignedInt()
does?
When I input "4294967295"
to that, and print the variable, it gives the output as -1
(-2
for 4294967294
, -3
for 4294967293
and so on...)
有没有办法我仍然可以 4294967295
在变量中?
Is there a way that I can still have 4294967295
in a variable?
我在这里遗漏了什么吗?
Am I missing something here?
a=Integer.parseUnsignedInt("4294967295");
System.out.println(a);
这使得输出为 -1
但是我期望 4294967295
。
This gives the output as -1
but I expected 4294967295
.
推荐答案
您可以将该整数视为unsigned int通过调用 toUnsignedString()
:
You can view that integer as unsigned int by calling toUnsignedString()
:
int uint = Integer.parseUnsignedInt("4294967295");
System.out.println(Integer.toUnsignedString(uint));
您还可以调用其他一些将int解释为unsigned的方法。
You can also call some other methods that interpret that int as unsigned.
例如:
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)
这篇关于如何在java中输出无符号整数的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!