0

A C# system is generating data and providing data to another Java system using SBE(Simple Binary Encoding) by primitiveType="uint64" (long).

In Java, when data is received as primitive long it is overflowing and in few cases leading to –ve numbers.

How to handle this situation ?

9
  • 4
    ... not sending invalid values? Commented Mar 5, 2019 at 10:39
  • This shouldn't be happening, as C#'s uint64 should be analogous to Java's long. Can you include some data which is causing this problem? Commented Mar 5, 2019 at 10:41
  • 1
    you can use BigInteger Commented Mar 5, 2019 at 10:42
  • 2
    @TimBiegeleisen Presumably the difference is that uint64 is unsigned, whereas Java's long is signed. So any number in the top half of uint64's range will end up negative when it is interpreted as a long. Commented Mar 5, 2019 at 10:42
  • 2
    unsigned or signed does not really make a difference, you're just receiving 64 bits of data which you interpret as a number. What are you using this number for? Commented Mar 5, 2019 at 10:46

1 Answer 1

1

You can receive the unsigned long as long, as "long" as one does not calculate with the long. You can even display that long as unsigned using Long.toUnsignedString(n).

Otherwise store it in a BigInteger. Ideally loaded as 8 big-endian bytes.

// Some snippets, unordered, showing useful constructs.
long n = ...;
n = Long.reverseBytes();
byte[] bigendian = new byte[8];
ByteBuffer buf = ByteBuffer.wrap(bigendian); // .order(ByteOrder.LITTLE_ENDIAN);
buf.putLong(n);

// Creating a BigInteger from unsigned long's bytes, requiring big-endian order.
BigInteger num = new BigInteger(1, bigendian); // 1 = positive
Sign up to request clarification or add additional context in comments.

2 Comments

Even if you calculate with the long, you can usually get away with using methods like Long.divideUnsigned(). (The other basic arithmetic operations are identical in two's complement.)
@biziclop Thanks, I almost added divideUnsigned/remainderUnsigned myself. I find it remarkable that numbers > 2^63 are actually used.

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.