Java8无符号算术 [英] Java8 unsigned arithmetic

查看:102
本文介绍了Java8无符号算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

广泛报道Java 8具有对无符号整数的库支持.但是,似乎没有文章解释如何使用它以及有多少可能.

Java 8 is widely reported to have library support for unsigned integers. However, there seem to be no articles explaining how to use it and how much is possible.

诸如Integer.CompareUnsigned之类的某些函数很容易找到并且似乎可以完成预期的工作.但是,我什至无法编写一个简单的循环,该循环在无符号long范围内循环两个的所有幂.

Some functions like Integer.CompareUnsigned are easy enough to find and seem to do what one would expect. However, I fail to write even a simple loop that loops over all powers of two within the range of unsigned long.

int i = 0;
for(long l=1; (Long.compareUnsigned(l, Long.MAX_VALUE*2) < 0) && i<100; l+=l) {
    System.out.println(l);
    i++;
}

产生输出

1
2
4
8
...
1152921504606846976
2305843009213693952
4611686018427387904
-9223372036854775808
0
0
0
...
0

我是否缺少某些内容?还是此简单任务仍需要外部库?

Am I missing something or are external libraries still required for this simple task?

推荐答案

如果您指的是

(Long.compareUnsigned(l, Long.MAX_VALUE*2) < 0)

l达到

-9223372036854775808

未签名是

9223372036854775808

Long.MAX_VALUE*2

18446744073709551614

所以在无符号世界中,l小于Long.MAX_VALUE*2.

So l is smaller than Long.MAX_VALUE*2 in the unsigned world.

假设您要查询的是0's

Assuming you're asking about the 0's

0
0
0
...
0

问题(如果您这样看)是,对于long(其他数字基元),第一位是符号位.

the problem (if you see it that way) is that, for long (other numerical primitives), the first bit is the sign bit.

如此

10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

-9223372036854775808

完成时

-9223372036854775808 + -9223372036854775808

您因为以下原因而下溢(上溢?)

you underflow (overflow?) since

    10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
+   10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

为0.在以后的循环迭代中,0 + 0保持为0.

which is 0. On later loop iterations, 0 + 0 remains 0.

这篇关于Java8无符号算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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