1

我想在另一个 ByteArray 之间的任何地方插入一个 ByteArray

var main: ByteArray = ...;
var bytes2insert: ByteArray = ...;
var index: int = ...;
// index is 0 to main.length and tells me where to write the bytes2insert in main
main.writeBytes(bytes2insert, index, bytes2insert.length);

如果我尝试使用随机索引的 writeBytes,我会因为“IndexOutOfBounds”之类的东西而出错。如何实现插入?我可能会摆脱一些 for 循环,但出于性能原因,我想(主要)使用给定的方法。


编辑:我认为 AS-3 文档有点缺乏(虽然没有检查 adobe.com)

// since the script needs to read from bytes2insert and write to main
// main.writeBytes(array, offset, length);
main.position = <start index for writing> // (seems to be important in this case)
offset = <start index for reading> // (I misunderstood that one)
length = <length for both>
4

1 回答 1

1

解决方案:

public function astest()
{
    var main: ByteArray = new ByteArray();
    var bytes2insert: ByteArray = new ByteArray();
    var index: int = 5;

    for(var i:int = 0; i < 20; i++)
        main.writeByte(99);
    for(var j:int = 0; j < 30; j++)
        bytes2insert.writeByte(100);

    trace("1", main);
    insertBytes(main, bytes2insert, index);
    trace("2", main);
}

private function insertBytes(target:ByteArray, insert:ByteArray, index:int):void
{
    if(index < target.length)
    {
        var tmp:ByteArray = new ByteArray();
        tmp.writeBytes(target, index);

        target.position = index;
        target.writeBytes(insert);
        target.writeBytes(tmp);
    }
}

//output:
//1 cccccccccccccccccccc
//2 cccccddddddddddddddddddddddddddddddccccccccccccccc
于 2013-06-05T08:38:53.493 回答