Federico
Federico

Reputation: 1157

Convert Bits to Bytes in Node-Red

I'm new to JavaScript and I use Node-Red to read an write from a Database.

I receive from the database an object that contains the status of 8 digital inputs. Each inputs is represented as a bit.

I'm looking for a method to combine each bits into a byte.

This is the object that I receive from the database:

array[1]
  0: object
    idx: 10
    ts: "2018-11-21T06:12:45.000Z"
    in_0: 1
    in_1: 1
    in_2: 1
    in_3: 1
    in_4: 1
    in_5: 1
    in_6: 1
    in_7: 1

in_x represent the input position.

As out I would like to receive a byte that represent the combination of each single byte.

For example:

in0: 0, in1: 1, in2: 0, in3: 0, in4: 0, in5: 1, in6: 0, in7: 0,

The output byte will be: 00100001 in binary that converted to byte is 33

Any suggestions?

Thanks in advance.

Upvotes: 1

Views: 1727

Answers (1)

Gary Ott
Gary Ott

Reputation: 380

The following code works as you requested*:

var output = 
    arr[0].in_0 + 
    (arr[0].in_1 << 1) +
    (arr[0].in_2 << 2) +
    (arr[0].in_3 << 3) +
    (arr[0].in_4 << 4) +
    (arr[0].in_5 << 5) +
    (arr[0].in_6 << 6) +
    (arr[0].in_7 << 7);

This code assumes that each variable can only be a 1 or a 0. Anything else will result in nonsense.

I have used the Left Bit Shift operator (<<) to obtain the power of two for each on bit.

You have specified that in_7 is the Most Significant Bit. If it is actually the Least Significant Bit, reverse the order of the in_x variables.

*The result is not a byte, but it does contain the number that I think you're expecting.

Upvotes: 1

Related Questions