Java:实现无符号 128 位整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1096964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:10:00  来源:igfitidea点击:

Java: Implementing a Unsigned 128bit Integer

javaintegerimplementation

提问by Ande Turner

first off I should ask:
Does anyone knows of a current implementation 128b UINT for Java?

首先我应该问:
有谁知道 Java 的当前实现 128b UINT?

I need something to hold natural cardinal values. ie: A huge counter.
I know of BigIntegers, which are slow and immutable. A 128b UINT makes sense ...

我需要一些东西来保存自然基数。即:一个巨大的柜台。
我知道 BigIntegers,它缓慢且不可变。128b UINT 是有道理的......

I was thinking about implementing an OWORD, using a pair of primitive longs.

我正在考虑使用一对原始 long 来实现 OWORD。

Overflows would throw an Exception and not Wraparound.

溢出会抛出异常而不是环绕。

What example sourcecode/blogs should I look to for implementing the workings of this class?

我应该寻找哪些示例源代码/博客来实现此类的工作?

回答by starblue

I would use 32 bit integers as the representation, because you need a bigger type (long) to get the extra precision for the carry bit, overflow detection and multiplication. Think of a 32 bit integer as a digit and apply the algorithms from primary school.

我将使用 32 位整数作为表示,因为您需要更大的类型(long)来获得进位、溢出检测和乘法的额外精度。将 32 位整数视为数字并应用小学的算法。

回答by fortran

Don't tell me that you plan to have 128 static setters and getters, one for each bit??? I'd definitively go for setBit(int index, boolean value) and getBit(int index) as instance methods.

不要告诉我你计划有 128 个静态 setter 和 getter,每一位一个????我肯定会选择 setBit(int index, boolean value) 和 getBit(int index) 作为实例方法。

More things you need: a toString() method so you can get a human readable representation (at some point you will want to print the numbers, I think).

你需要更多的东西:一个 toString() 方法,这样你就可以获得人类可读的表示(我认为在某些时候你会想要打印数字)。

Remember that all the ordinal types in java are signed (with the exception of char), so if you plan to use two longs, keep always in mind that the lower part could be problematic for detecting overflows and such... anyway, you will have a 127 bit number unless because the lower part would be treated as a 63 bit unsigned.

请记住,java 中的所有序数类型都是有符号的(char 除外),因此如果您打算使用两个 long,请始终牢记下半部分可能会导致检测溢出等问题……无论如何,您将有一个 127 位的数字,除非因为较低的部分将被视为 63 位无符号。

回答by PaulJWilliams

Why not use BigInteger?

为什么不使用 BigInteger?