1

I'm trying to use BigInteger for representing an unsigned 64 bit (long) coming from C in java and my approach is exactly same as mentioned in the following post.

http://technologicaloddity.com/2010/09/22/biginteger-as-unsigned-long-in-java/

Can one of you please validate that this approach is correct?

Any help in this regard appreciated.

0

1 Answer 1

8

Certainly, but do you really need it? There's a major performance cost. The only time you need it unsigned is when comparing, which you can fix with a small unsigned-compare method. The rest of the time you can just use a long.

Sign up to request clarification or add additional context in comments.

7 Comments

+1, and you don't need to write your own method. I'm sure many libraries for doing unsigned operations exist; Guava is one: docs.guava-libraries.googlecode.com/git/javadoc/com/google/…
Thank you for confirming. The usecase is not very performance sensitive, so I'm not much concerned on that point.Still for a better understanding, how the case unsigned c Long.MAX will be mapped to java long if I use long as you mentioned.or may be I missed some point. @Mark, I came across the guava library, but in my case I have only one scenario where I need this operation, so didnt bring a new library.
If performance isn't an issue then I would personally use the Guava UnsignedLong wrapper as it removes any ambiguity as to the number is representing.
@Aham A long has 64 bits, whether signed or unsigned. The only difference is whether it compares < 0 or not. -Long.MAX_VALUE is, not just 'maps to' 0x8000000000000001, unless I have fouled up my twos-complement again.
You can compare two unsigned longs with a + Long.MIN_VALUE <=> b + Long.MIN_VALUE where <=> is your choice of comparison. for == and != you can just compare a and b. Operations +, -, <<, >>> and * work the same way. / and '%' are different if the top bit is set.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.