AmbGup
AmbGup

Reputation: 771

Java primitive long overflow

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 ?

Upvotes: 0

Views: 195

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109557

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

Upvotes: 1

Related Questions