2013-06-05 30 views
1

我想在任何地方插入另一個的ByteArrayAS-3 - 如何將一個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); 

之間的ByteArray如果我嘗試用隨機指數我得到的,因爲「IndexOutOfBounds」錯誤writeBytes和東東。我怎樣才能實現插入?我可能會逃脫一些for循環,但出於性能原因,我想(主要)使用給定的方法。


編輯:我認爲,AS-3文檔是有點lacky(沒有檢查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> 

回答

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