Search code examples
javascriptarraybuffer

Convert part of an ArrayBuffer to a string


I have a C# App that, using WebSockets sends an ArrayBuffer to my Javascript client. The 1st 2 byte are int values (8 bit).

The next 17 bytes represent a string of 17 chars.

The rest is an image array.

Now, I can read the 1st 2 bytes to get my ints. I can also read the image. How do I read the string value which starts from the 2 index (using base index of 1) and the following 17 bytes?

So, my code so far is:

var len = e.data.byteLength;
var dv = new DataView(e.data);
var liveViewIndex = dv.getInt8(0);
var tripped = dv.getInt8(1);
//need to get 17 char string here!!
var frame = e.data.slice(19, len - 19);
desktopImage.src = 'data:image/jpeg;base64,' + base64ArrayBuffer(frame);

thanks


Solution

  • Given that the string is encoded as simple ASCII, the following should work:

    var string = String.fromCharCode.apply(String, new Uint8Array(e.data, 2, 17));
    

    It first creates a Uint8Array view on the interesting part of the buffer, and then uses it as arguments to String.fromCharCode.