本文翻译自:Declaring an unsigned int in Java
Is there a way to declare an unsigned int in Java? 有没有办法在Java中声明一个无符号的int?
Or the question may be framed as this as well: What is the Java equivalent of unsigned? 或也可以这样构想这个问题:Java的unsigned等同于什么?
Just to tell you the context I was looking at Java's implementation of String.hashcode()
. 只是为了告诉您上下文,我正在查看Java的String.hashcode()
。 I wanted to test the possibility of collision if the integer were 32 unsigned int. 我想测试整数是否为32 unsigned int时发生冲突的可能性。
#1楼
参考:https://stackoom.com/question/fLWA/在Java中声明一个unsigned-int
#2楼
You can use the Math.abs(number) function. 您可以使用Math.abs(number)函数。 It returns a positive number. 它返回一个正数。
#3楼
Java 8中有一个用于未签名的Integer和Long的API!
#4楼
Whether a value in an int is signed or unsigned depends on how the bits are interpreted - Java interprets bits as a signed value (it doesn't have unsigned primitives). 一个int值是带符号的还是无符号的,取决于位的解释方式-Java将位解释为带符号的值(它没有无符号的原语)。
If you have an int that you want to interpret as an unsigned value (eg you read an int from a DataInputStream that you know contains an unsigned value) then you can do the following trick. 如果您有一个要解释为无符号值的整数(例如,从知道包含无符号值的DataInputStream读取一个整数),则可以执行以下技巧。
int fourBytesIJustRead = someObject.getInt();
long unsignedValue = fourBytesIJustRead & 0xffffffffl;
Note, that it is important that the hex literal is a long literal, not an int literal - hence the 'l' at the end. 请注意,十六进制字面量是一个长字面量,而不是整数字面量是很重要的,因此末尾为“ l”。
#5楼
For unsigned numbers you can use these classes from Guava library : 对于无符号数字,您可以使用Guava库中的以下类:
They support various operations: 它们支持各种操作:
- plus 加
- minus 减去
- times 次
- mod 模
- dividedBy 除以
The thing that seems missing at the moment are byte shift operators. 目前似乎缺少的是字节移位运算符。 If you need those you can use BigInteger from Java. 如果需要这些,可以使用Java的BigInteger。
#6楼
We needed unsigned numbers to model MySQL's unsigned TINYINT
, SMALLINT
, INT
, BIGINT
in jOOQ , which is why we have created jOOU , a minimalistic library offering wrapper types for unsigned integer numbers in Java. 我们需要无符号数来建模jOOQ中 MySQL的无符号TINYINT
, SMALLINT
, INT
, BIGINT
,这就是为什么我们创建了jOOU的原因,这是一个简约的库,为Java中的无符号整数提供包装类型。 Example: 例:
import static org.joou.Unsigned.*;
// and then...
UByte b = ubyte(1);
UShort s = ushort(1);
UInteger i = uint(1);
ULong l = ulong(1);
All of these types extend java.lang.Number
and can be converted into higher-order primitive types and BigInteger
. 所有这些类型都扩展了java.lang.Number
并且可以将其转换为高阶原始类型和BigInteger
。 Hope this helps. 希望这可以帮助。
(Disclaimer: I work for the company behind these libraries) (免责声明:我为这些库背后的公司工作)