Reading bytes from a JavaScript string

前端 未结 9 1332
悲哀的现实
悲哀的现实 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条回答
  •  旧时难觅i
    2020-11-28 03:37

    How did you get the binary data into the string in the first place? How the binary data gets encoded into a string is an IMPORTANT consideration, and you need an answer to that question before you can proceed.

    One way I know of to get binary data into a string, is to use the XHR object, and set it to expect UTF-16.

    Once it's in utf-16, you can retrieve 16-bit numbers from the string using "....".charCodeAt(0)

    which will be a number between 0 and 65535

    Then, if you like, you can convert that number into two numbers between 0 and 255 like this:

    var leftByte = mynumber>>>8;
    var rightByte = mynumber&255;
    

提交回复
热议问题