gpt4 book ai didi

java - BigInteger 无符号左移或右移

转载 作者:行者123 更新时间:2023-12-04 17:52:33 24 4
gpt4 key购买 nike

我正在 int 中使用 BigInteger 重新实现一个函数。现在有步骤

h = n >>> log2n--

但我在这里遇到了麻烦。原代码中 h、n、log2n 都是 int 类型,如果我将 h、n、log2n 设置为 BigInteger,上面代码的等价表达式是什么?如何在 BigInteger 中执行无符号右移 (>>>)?

编辑:
代码块是:
int log2n = 31 - Integer.numberOfLeadingZeros(n);
int h = 0, shift = 0, high = 1;

while (h != n)
{
shift += h;
h = n >>> log2n--;
int len = high;
high = (h & 1) == 1 ? h : h - 1;
len = (high - len) / 2;

if (len > 0)
{
p = p.multiply(product(len));
r = r.multiply(p);
}
}

最佳答案

引用 Java 文档:

The unsigned right shift operator (>>>) is omitted, as this operation makes little sense in combination with the "infinite word size" abstraction provided by this class.



-1 的 32 位整数表示为(二进制)
11111111 11111111 11111111 11111111

如果您对此使用带符号的右移运算符( >> ),您将得到
11111111 11111111 11111111 11111111 

即同样的事情。如果您对此使用无符号右移运算符,移动 1,您将得到
01111111 11111111 11111111 11111111.

但是 BigInteger 的长度是无限的。 BigInteger 中 -1 的表示理论上是
11111111 111... infinite 1s here..... 11111111

无符号右移运算符意味着您将 0 放在最左边的点 - 这是无穷大。由于这没有什么意义,因此省略了运算符。

至于您的实际代码,您现在需要做什么取决于周围的代码在做什么以及为什么为原始代码选择无符号移位。就像是
n.negate().shiftRight(log2n)

可能会起作用,但这一切都取决于具体情况。

关于java - BigInteger 无符号左移或右移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5281852/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com