在Java中声明一个unsigned int

Java不直接支持无符号整数,但可以通过Math.abs()函数、Java 8的API、Guava库或jOOU库来实现无符号整数的操作。例如,使用Math.abs()确保数值为正,或者使用jOOU库提供无符号整数的包装类型。
摘要由CSDN通过智能技术生成

本文翻译自: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和LongAPI!


#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的无符号TINYINTSMALLINTINTBIGINT ,这就是为什么我们创建了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) (免责声明:我为这些库背后的公司工作)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值