本文介绍了如何在Java 8和Java 9中使用unsigned Integer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Oracle原始数据类型中,它提到Java 8增加了对无符号整数和长整数的支持:

In the Oracle "Primitive data types" page, it mentions that Java 8 adds support for unsigned ints and longs:

long long 数据类型是64位二进制补码整数。签名的 long 的最小值为-2 ,最大值为2 -1。 在Java SE 8及更高版本中,您可以使用 long 数据类型来表示无符号的64位 long ,其最小值为0,最大值为2 -1。当需要比int提供的值更宽的值时,请使用此数据类型。 Long 类还包含 compareUnsigned divideUnsigned 等方法支持无符号 long 的算术运算。

long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of −2 and a maximum value of 2−1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 2−1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

然而,我找不到办法声明无符号长整数。例如,下面的代码给出了编译器错误消息文字超出范围(我当然使用的是Java 8),当它应该在范围内时(指定的值恰好为2 -1):

However, I find no way to declare an unsigned long or integer. The following code, for example, gives a compiler error message of "the literal is out of range" (I'm using Java 8, of course), when it should be in range (the value assigned is precisely 2−1):

public class Foo {
    static long values = 18446744073709551615L;

    public static void main(String[] args){
        System.out.println(values);
    }
}

那么,有没有办法声明一个unsigned int或者很长?

So, is there any way to declare an unsigned int or long?

推荐答案

根据您发布的文档和 - 在无符号int / long和签名之间声明原语时没有区别。 新支持是在Integer和Long类中添加静态方法,例如 Integer.divideUnsigned 。如果您没有使用这些方法,那么长于2 ^ 63-1的无符号只是一个带有负值的普通旧长。

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

从快速浏览,看起来有一种方法可以在+/- 2 ^ 31-1或+/- 2 ^ 63-1之外的范围内声明整数常量。您必须手动计算与超出范围正值相对应的负值。

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

这篇关于如何在Java 8和Java 9中使用unsigned Integer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 15:36