Java: Implementing a Unsigned 128bit Integer

血红的双手。 提交于 2020-01-01 04:21:04

问题


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

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 ...

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

Overflows would throw an Exception and not Wraparound.

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


回答1:


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.




回答2:


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.

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).

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.




回答3:


Why not use BigInteger?



来源:https://stackoverflow.com/questions/1096964/java-implementing-a-unsigned-128bit-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!