java - 在 Java 中声明一个 unsigned int

标签 java integer unsigned

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

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

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

最佳答案

Java 没有 unsigned integers 的数据类型.

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

您也可以像使用无符号整数一样使用有符号整数。 two's complement representation的好处|是大多数操作(例如加法、减法、乘法和左移)在二进制级别上对于有符号和无符号整数是相同的。然而,一些操作(除法、右移、比较和强制转换)是不同的。从 Java SE 8 开始,Integer 中的新方法类允许您充分使用 int 数据类型 to perform unsigned arithmetic :

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 类中的这些方法来进行无符号运算。

关于java - 在 Java 中声明一个 unsigned int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9854166/

相关文章:

java - 比较整数的奇怪错误

c - 如何确定变量是有符号的还是无符号的?

syntax - VHDL 将十进制值分配给 std_logic_vector

Java:不可变到不可变的转换

java - 如何在 jar 文件中制作 Frame/Applet 应用程序?

java - Objectify BATCH delete 无效

java - 更改最终 Integer 变量的值

java - EJB 3.1 session bean 未显示在 WebLogic 12c JNDI 树中

c - 没有 float 的有效计算方法,C

c - 无符号整数的for循环