How do I read binary data to a byte array in Javascript?

后端 未结 2 1433
旧时难觅i
旧时难觅i 2020-11-30 09:07

I want to read a binary file in JavaScript that would be gotten through XMLHttpRequest and be able to manipulate that data. From my researching I discovered this method of r

2条回答
  •  渐次进展
    2020-11-30 09:33

    I'm sure you will find this helpful: http://jsdo.it/tsmallfield/uint8array.

    Click on javascript tab. There will appear the code to convert the Uint8Array in a string. The author shows 2 method:

    • The first is about creating a view.
    • The second offsetting bytes.

    EDIT: report the code for completeness

    var buffer = new ArrayBuffer( res.length ), // res is this.response in your case
        view   = new Uint8Array( buffer ),
        len    = view.length,
        fromCharCode = String.fromCharCode,
        i, s, str;    
    
    /**
     *  1) 8bitの配列に入れて上位ビットけずる
     */
    str = "";
    
    for ( i = len; i--; ) {
      view[i] = res[i].charCodeAt(0);
    }
    
    for ( i = 0; i < len; ++i ) {
      str += fromCharCode( view[i] );
    }    
    
    /**
     *  2) & 0xff で上位ビットけずる
     */
    str = "";
    
    for ( i = 0; i < len; ++i ) {
      str += fromCharCode( res[i].charCodeAt(0) & 0xff );
    }
    

提交回复
热议问题