问题
I have a nodejs script where I'd like to parse MP3 frames. Those frames are easy to detect since each frame starts with the two bytes 0xff 0xfb
.
I'm using a Uint8Array
to access the bytes of that file. Using [].indexOf.call(data, 0xff)
I can easily search for a single byte but not for two bytes. Obviously I could check the second byte manually but I wonder if there's a clean way to get the index of a certain byte sequence.
回答1:
Apparently there is no nice way to do this without writing custom code so that's what I did:
Uint8Array.prototype.indexOfMulti = function(searchElements, fromIndex) {
fromIndex = fromIndex || 0;
var index = Array.prototype.indexOf.call(this, searchElements[0], fromIndex);
if(searchElements.length === 1 || index === -1) {
// Not found or no other elements to check
return index;
}
for(var i = index, j = 0; j < searchElements.length && i < this.length; i++, j++) {
if(this[i] !== searchElements[j]) {
return this.indexOfMulti(searchElements, index + 1);
}
}
return(i === index + searchElements.length) ? index : -1;
};
来源:https://stackoverflow.com/questions/14147213/search-for-multi-byte-pattern-in-uint8array