Search for multi-byte pattern in Uint8Array

天大地大妈咪最大 提交于 2021-02-18 07:41:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!