問題描述
有沒有辦法在 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.
這篇關于在 Java 中聲明一個 unsigned int的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!