2011-11-10 62 views
2

here的Javascript二进制文件读取

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

_readByte: function (i, size) { 
     return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff; 
    }, 

_readBits: function (start, length, size) { 
     var offsetLeft = (start + length) % 8; 
     var offsetRight = start % 8; 
     var curByte = size - (start >> 3) - 1; 
     var lastByte = size + (-(start + length) >> 3); 
     var diff = curByte - lastByte; 

     var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1); 

     if (diff && offsetLeft) { 
      sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight; 
     } 

     while (diff) { 
      sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight); 
     } 

     return sum; 
    }, 

此代码的二进制文件的阅读。不幸的是,这个代码没有记录。 我想了解它是如何工作的。 (特别是_readBits和_shl方法) 在_readBits什么是offign的?也curByte和lastByte: 我认为这样的方式:

_readBits(0,16,2)curByte成为1. lastByte成为0.为什么lastByte小于curByte?或者我犯了一个错误?哪里?请帮忙!

+0

@ Bakudan-ханювиги这并不奇怪,注意'++ b'只执行一次。 – ExpExc

+0

我更喜欢binaryAjax.js - http://www.nihilogic.dk/labs/binaryajax/binaryajax.js - 你可以在它的网站上找到一些帮助。 – Luc125

回答

0
  • _readByte(i, size)size是在字节的缓冲区长度,i是要读取字节的逆转指数(从缓冲区末尾索引,而不是从一开始)。
  • _readBits(start, length, size)size是在字节的缓冲区长度,length是要读取的比特数,start是要读出的第一位的索引
  • _shl(a, b):将读取字节a转换为基于其索引b的实际值。

因为_readByte使用反转索引,所以lastByte小于curByte

offsetLeftoffsetRight用于分别从lastBytecurByte中删除无关位(不在读取范围内的位)。

0

我不确定代码是如何跨浏览器的。我使用下面的方法来读取二进制数据。 IE浏览器有一些无法用Javascript解决的问题,你需要用VB编写的小型帮助函数。 Here是一个完全跨浏览器的二进制阅读器类。如果你只是想,如果没有所有的辅助功能重要的位,只需添加到您的类需要读取二进制结尾:

// 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" 
    ); 
} 

然后你就可以挑什么就在你的类中添加:

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

现在你可以读取的字节中所有你想要

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