0

If I have a string with ones and zeros, like this:

"0101101"

Is there anyway I can send only those bits, with the WebSocket.prototype.send method?

First I have to convert them into an ArrayBuffer, how would I do that?

If I just send the string, each 1 and 0 would be 1 byte long (since they are chars and not bits, and UTF-8 encoded), that wouldnt just work, how can I convert these string-bits into an ArrayBuffer and send them?

No, this is not a dublicate since it's not about converting a bitstring to int values. It's about converting it to an ArrayBuffer

1 Answers1

0

as you already implicit said, there is no direct way to send a bit array directy through the websocket api. You need to convert it to an ArrayBuffer. Since ArrayBuffer can not be modified directly, but only through an TypedArray, I'd suggest to:

  • may prepend your string with leading zeros as required
  • split your string into parts of 8 bits
  • parsing integers out of the bits
  • adding these integers to an Uint8Array
  • getting the buffer from the array
  • sending the buffer through websocket

This could look like follows:

function binaryStringToArrayBuffer(data) {

    while (data.length % 8 != 0) {
        data = '0' + data;
    }

    var buf = new ArrayBuffer(data.length / 8);
    var result = new Uint8Array(buf);


    var dataArray = data.split('');

    var idx = 0;
    while(dataArray.length > 0) {
        var bits = dataArray.splice(0, 8);
        var bitsAsInt = parseInt(bits.join(''), 2);

        result[idx] = bitsAsInt;
        idx++;
    }
    return result.buffer;
}

var data = "01010111101011010111110001100000000000000101001";
var buffer = binaryStringToArrayBuffer(data);

getYourWebSocket().send(buffer);
Martin Ackermann
  • 884
  • 6
  • 15