I am BigInt numbers that consist of two Long each of the following ways:
val msb = -1L // some arbitrary long value, can be anything between Long.Min/MaxValue val lsb = 25L // a second arbitrary long value val bb = ByteBuffer .allocate(17) .put(0.toByte) // 1 byte .putLong(msb) // 8 bytes .putLong(lsb) // 8 bytes val number = BigInt(bb.array) // in this case: 340282366920938463444927863358058659865
The reason I add another 0- Byte to the front is to ensure that the result is a positive number. Otherwise, the result of BigInt may be negative due to two additions. An algorithm that is called subsequently expects numbers to be greater than or equal to zero.
So far so good.
I'm having trouble reversing this entire process - converting BigInt back to two Long (exactly the two values ββthat were used as input). I can't just do the following:
val arr = number.toByteArray val bb = ByteBuffer.wrap(arr) val ignore = bb.getByte val msb = bb.getLong val lsb = bb.getLong
Imagine the number of BigInt is equal, for example. 3. Then .toByteArray will result in an array of size 1, not 16 (or 17), and therefore calls to getLong will BufferUnderflowException .
What is the easiest way to solve this problem? I tried several ways to manually fill the buffer until 16 bytes are available, but since this "filling" should correctly account for the two additions of these two numbers, I was not successful.
java arrays scala bytebuffer
ceran
source share