Skip to content Skip to sidebar Skip to footer

Javascript Binary File Reading

From here: _shl: function (a, b){ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); return

Solution 1:

  • _readByte(i, size): size is the buffer length in byte, i is the reversed index (index from the end of the buffer, not from the start) of the byte which you want to read.
  • _readBits(start, length, size): size is the buffer length in byte, length is the number of bits which you want to read, start is the the index of the first bit which you want to read.
  • _shl(a, b): convert read byte a to actual value based on its index b.

Because _readByte use reversed index, so lastByte less than curByte.

offsetLeft and offsetRight are used to remove unrelated bits (bits not in read range) from lastByte and curByte respectively.


Solution 2:

I'm not sure how cross-browser the code is. I've used the method below for reading binary data. IE has some issues that can't be resolved with only Javascript, you need a small helper function written in VB. Here is a fully cross browser binary reader class. If you just want the bits that matter without all the helper functionality, just add this to the end of your class that needs to read binary:

// Add the helper functions in vbscript for IE browsers
// From https://gist.github.com/161492
if ($.browser.msie) {
    document.write(
        "<script type='text/vbscript'>\r\n"
        + "Function IEBinary_getByteAt(strBinary, iOffset)\r\n"
        + " IEBinary_getByteAt = AscB(MidB(strBinary,iOffset+1,1))\r\n"
        + "End Function\r\n"
        + "Function IEBinary_getLength(strBinary)\r\n"
        + " IEBinary_getLength = LenB(strBinary)\r\n"
        + "End Function\r\n"
        + "</script>\r\n"
    );
}

Then you can pick whats right in your class add:

// Define the binary accessor function
if ($.browser.msie) {
        this.getByteAt = function(binData, offset) {
        return IEBinary_getByteAt(binData, offset);
    }
} else {
    this.getByteAt = function(binData, offset) {
        return binData.charCodeAt(offset) & 0xFF;
    }
}

Now you can read the bytes all you want

var byte = getByteAt.call(this, rawData, dataPos);

Solution 3:

I found this one and it is very well documented: https://github.com/vjeux/jParser


Post a Comment for "Javascript Binary File Reading"