I want to add 5 sets of integer into a ByteArray `...
# getting-started
v
I want to add 5 sets of integer into a ByteArray
Copy code
val byteArray = ByteBuffer.allocate(16)
                        .putInt(firstInteger)
                        .putInt(secondInteger)
                        .put(ByteBuffer.allocate(2).put(thirdInteger.toByte()))
                        .put(ByteBuffer.allocate(3).put(fourthInteger.toByte()))
                        .put(ByteBuffer.allocate(3).put(fifthInteger.toByte()))
                        .array()
Then I try to read them like this
Copy code
val firstData = byteArray.copyOfRange(0, 4)
                val secondData = byteArray.copyOfRange(4, 8)
                val thirdData = byteArray.copyOfRange(8,10)
                val forthData = byteArray.copyOfRange(10, 13)
                val fifthData = byteArray.copyOfRange(13, 16)
But when I try to wrap each of them back to
Integer
, I got exception
BufferUnderFlow
when trying to wrap 2 bytes and 3 bytes
Integer
Copy code
ByteBuffer.wrap(thirdData).int.should.be.equal(thirdInteger)
ByteBuffer.wrap(thirdData,0,2).int.should.be.equal(thirdInteger)
My question is, how to wrap 2 or 3 bytes into an
Integer
? and does my first part of the code to create the
ByteArray
is correct?