我在获取ByteArray
数据的一部分时遇到问题。fileData
中有一个二进制文本:
var fileData:ByteArray = new ByteArray();
//..........here's code that fills this var with binary data
.....readBytes(fileData,0,1000);
//
数据是这样的:
йYЯyeSВ–нkq(г<<<start>>>:xЪмЅdf”cйxЪsdfмЅ”cйdxЪмЅ”cй<<<end>>>В–нkВ
因此,我需要找到
<<< start >>>
和<<< end >>>
的位置并复制位于两者之间的数据。但是搜索
fileData.toString().indexOf('<<< start >>>')
有时会得到该字符串错误的位置,有时甚至根本找不到它。如何正确确定我需要的部分数据的位置?
最佳答案
由于正在使用二进制数据,因此不应使用fileData.toString().indexOf()
。您必须搜索一个字节序列。
以下函数检索指定模式的位置:
public function indexOf(bytes:ByteArray, search:String, startOffset:uint = 0):void
{
if (bytes == null || bytes.length == 0) {
throw new ArgumentError("bytes parameter should not be null or empty");
}
if (search == null || search.length == 0) {
throw new ArgumentError("search parameter should not be null or empty");
}
// Fast return is the search pattern length is shorter than the bytes one
if (bytes.length < startOffset + search.length) {
return -1;
}
// Create the pattern
var pattern:ByteArray = new ByteArray();
pattern.writeUTFBytes(search);
// Initialize loop variables
var end:Boolean;
var found:Boolean;
var i:uint = startOffset;
var j:uint = 0;
var p:uint = pattern.length;
var n:uint = bytes.length - p;
// Repeat util end
do {
// Compare the current byte with the first one of the pattern
if (bytes[i] == pattern[0]) {
found = true;
j = p;
// Loop through every byte of the pattern
while (--j) {
if (bytes[i + j] != pattern[j]) {
found = false;
break;
}
}
// Return the pattern position
if (found) {
return i;
}
}
// Check if end is reach
end = (++i > n);
} while (!end);
// Pattern not found
return -1;
}
然后您可以通过以下方式使用该函数:
var extractedBytes = new ByteArray();
var startPos:int = indexOf(fileData, "<<<start>>>");
var endPos:int;
if (startPos == -1) {
trace("<<<start>>> not found");
} else {
endPos = indexOf(fileData, "<<<end>>>", startPos + 11); // "<<<start>>>".length = 11
}
if (startPos == -1) {
trace("<<<end>>> not found");
} else {
// Extract the bytes between <<<start>>> and <<<end>>>
fileData.readBytes(extractedBytes, startPos + 11, endPos);
}
免责声明:我尚未测试我的代码!
关于actionscript-3 - Flash AS3-我需要对byteArray数据进行二进制搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11777348/