在 Java 中声明一个 unsigned int

2022-01-14 00:00:00 integer unsigned java

有没有办法在 Java 中声明一个 unsigned int?

Is there a way to declare an unsigned int in Java?

或者问题也可以这样表述:无符号的 Java 等价物是什么?

Or the question may be framed as this as well: What is the Java equivalent of unsigned?

只是为了告诉你我正在查看 Java 的 String.hashcode() 实现的上下文.如果整数是 32 unsigned int,我想测试碰撞的可能性.

Just to tell you the context I was looking at Java's implementation of String.hashcode(). I wanted to test the possibility of collision if the integer were 32 unsigned int.

推荐答案

Java 没有 无符号整数.

您可以定义一个 long 如果您需要存储大值,而不是 int.

您也可以像使用无符号整数一样使用有符号整数.二的补码表示的好处是大多数运算(例如加法、减法、乘法、和左移)在有符号和无符号整数的二进制级别上是相同的.然而,一些操作(除法、右移、比较和强制转换)是不同的.从 Java SE 8 开始, 中的新方法Integer 类允许您充分使用 int 数据类型 执行无符号算术:

You can also use a signed integer as if it were unsigned. The benefit of two's complement representation is that most operations (such as addition, subtraction, multiplication, and left shift) are identical on a binary level for signed and unsigned integers. A few operations (division, right shift, comparison, and casting), however, are different. As of Java SE 8, new methods in the Integer class allow you to fully use the int data type to perform unsigned arithmetic:

在 Java SE 8 及更高版本中,可以使用 int 数据类型来表示一个无符号的 32 位整数,其最小值为 0,最大值为 2^32-1.使用 Integer 类将 int 数据类型用作无符号整数.静态方法,例如 compareUnsigned, divideUnsigned 等已添加到 Integer 类中,以支持无符号整数的算术运算.

In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 2^32-1. Use the Integer class to use int data type as an unsigned integer. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

请注意,int 变量在声明时仍然是有符号的,但现在可以通过使用 Integer 类中的这些方法来进行无符号运算.

Note that int variables are still signed when declared but unsigned arithmetic is now possible by using those methods in the Integer class.

相关文章