Search code examples
javascriptnode-redbitstream

Javascript / Nodered function node: bitstream operations


Following task to do:

There is a protocol that defines minimalistic data like:

binary     0 1 0 0 0 1 1 1 0 0 1 1 1 0
variable   [-] [-----] [---] [-------]
name       a      b      c       d

where parameter "a" consists of 2 bits, parameter "b" of 5 bits and so on. I have to set them like

a=1
b=1
c=6
d=...

so the above bit buffer will automatically result.

This stream of bits shall be stored in a buffer like this:

let buf = Buffer.alloc(64, 0);

Is there a possibility to achive this?


Solution

  • There are a number of approaches to this.

    1. Using nodes like the node-red-contrib-buffer-parser which will allow you to do this as part of a flow

    2. Do basic bit shifting in function nodes. e.g.

      var a = 1
      var b = 16
      var c = 2
      var d = 10
      
      var answer  = a << 14 | b << 12 | c << 10 | d << 6
      

      which can then be written to a buffer.writeUint16()