在 Java 中声明一个无符号整数 [英] Declaring an unsigned int in Java

查看:57
本文介绍了在 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.

这篇关于在 Java 中声明一个无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆