简体   繁体   中英

Search for multi-byte pattern in Uint8Array

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM