Partition ByteArray to equally ByteArray of Queue

Viewed 184

So, I have a ByteArray of dynamic size from the server and I need to divide it into 15 equal size and add it to my Queue<ByteArray>. So how do I do this?

I need this for my BLE device actually. I'm doing a firmware update and I need to convert the bytearray into equally 20 bytes each inside the Queue so that it happens smoothly?

for example bytearray received from the server is 256. I want to have my

queue[0]=bytes[0-15] onpeek() 
queue[1]=bytes[16-30] onPeek()
queue[2]=bytes[31-45]onPeek()
 ...
....
queue[n]= bytes[240-255] onPeek()

My code:

private val sendQueue: Queue<ByteArray> = ConcurrentLinkedQueue()

    @Volatile
    private var isWriting = false


    fun send(
        dataByte: ByteArray,
        gatt: BluetoothGatt
    ): Int {
        var data = dataByte
        while (data.count() > 15) {

//            todo divide into 20 equal byte array and add it to sendQueue.
           
        }
        sendQueue.add(data)

        if (!isWriting) _send(gatt)
        return 0 //0
    }
2 Answers

You can try something like this (draft, not checking)

var partCount = 20;
var data = dataByte;
var len = data.getLength();
var partSize = len / partCount;  
for (int i = 0; i < partCount - 1; i++) {    
    var newArray = Arrays.copyOfRange(bytes, i * partSize, (i + 1) * partSize);
    sendQueue.add(newArray);
}
// and we added last part (may be a little bigger then other parts if "len % 20 != 0").
var newArray = Arrays.copyOfRange(bytes, partSize * (partCount - 1), len); 
sendQueue.add(newArray);

I'm not sure if understood your question but this can give a direction

dataByte.asIterable().chunked(15).forEach { 
    // 'it' is a List<Byte>, convert it to ByteArray in order to add it to queue.
    sendQueue.add(it.toByteArray())
}

referring dataByte as Iterable will allow you to chunk it to the size you want, then all you need is to iterate over it's results and add it to your queue.

Related