【问题标题】:Partition ByteArray to equally ByteArray of Queue将 ByteArray 分区到队列的同等 ByteArray
【发布时间】:2023-03-11 00:17:01
【问题描述】:

所以,我有一个来自服务器的动态大小 ByteArray,我需要将它分成15 个相等大小 并将其添加到我的Queue<ByteArray>。那我该怎么做呢?

我的 BLE 设备实际上需要这个。我正在进行固件更新,我需要将 bytearray 转换为 Queue 中的每个 20 个字节,以便顺利进行?

例如从服务器收到的字节数组是 256。我想要我的

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

我的代码:

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
    }

【问题讨论】:

  • 谁说你的数组长度平分到15?
  • @GhostCat 你能看到我的编辑吗?我想我现在清楚了吗?
  • 不,我不明白 3 个 15 字节的数组是如何产生 256 字节的。
  • @GhostCat 它将不断增加。直到找到匹配的数组。实际上。
  • 对不起,这对我来说仍然没有意义。努力写出超级简单的句子。主语动词宾语。给我们一个“完整”的例子。 3 * 15 不是 256。

标签: java android arrays kotlin


【解决方案1】:

你可以试试这样的(草稿,不检查)

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);

【讨论】:

    【解决方案2】:

    我不确定你是否理解了你的问题,但这可以给出一个方向

    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())
    }
    

    将 dataByte 称为Iterable 将允许您将chunk 设置为您想要的大小, 那么您所需要的就是迭代它的结果并将其添加到您的队列中。

    【讨论】:

    • 我认为获取列表的字节数组与列表的字节数组中的元素不同。所以这可能行不通。
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2015-08-28
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多