Reading bytes from a JavaScript string

前端 未结 9 1330
悲哀的现实
悲哀的现实 2020-11-28 02:46

I have a string containing binary data in JavaScript. Now I want to read, for example, an integer from it. So I get the first 4 characters, use charCodeAt, do s

9条回答
  •  醉酒成梦
    2020-11-28 03:18

    I believe that you can can do this with relatively simple bit operations:

    function stringToBytes ( str ) {
      var ch, st, re = [];
      for (var i = 0; i < str.length; i++ ) {
        ch = str.charCodeAt(i);  // get char 
        st = [];                 // set up "stack"
        do {
          st.push( ch & 0xFF );  // push byte to stack
          ch = ch >> 8;          // shift value down by 1 byte
        }  
        while ( ch );
        // add stack contents to result
        // done because chars have "wrong" endianness
        re = re.concat( st.reverse() );
      }
      // return an array of bytes
      return re;
    }
    
    stringToBytes( "A\u1242B\u4123C" );  // [65, 18, 66, 66, 65, 35, 67]
    

    It should be a simple matter to sum the output up by reading the byte array as if it were memory and adding it up into larger numbers:

    function getIntAt ( arr, offs ) {
      return (arr[offs+0] << 24) +
             (arr[offs+1] << 16) +
             (arr[offs+2] << 8) +
              arr[offs+3];
    }
    
    function getWordAt ( arr, offs ) {
      return (arr[offs+0] << 8) +
              arr[offs+1];
    }
    
    '\\u' + getWordAt( stringToBytes( "A\u1242" ), 1 ).toString(16);  // "1242"
    

提交回复
热议问题