Binary Data
Estimated reading time: 2 minutes
Function Nodes can convert data into binary for viewing and performing operations on individual bits of data.
Create the Flow
To create a flow that converts data into binary and can show individual bits of data:
-
Connect an Inject node, a Function node, and a Debug node as pictured below in the final result:
-
Double-click the Function node and enter the following lines of code:
function decimalToBinary (decimal) { // Declares a function, named decimalToBinary, that converts decimal to binary. return decimal.toString(2); // Converts decimal into binary by passing in 2 (for base 2) into toString. } function getBit (number, bit) { // Declares a function to get a single bit from a number. /* ANDs the number with 00000001 shifted by the bit you want to get. In this example, * we get the second bit from 3 (0000011 in binary), by ANDing with 00000010 to get the 2nd bit. */ var bit = number & (1 << bit); /* If we output bit as is, it will show up as "10". The following if statement * ensures that our output will just be "1" or "0". */ if (bit == 0) { return 0; } return 1; } var decimal = msg.payload; // Assigns the number from the msg payload to a variable, called decimal. var binary = decimalToBinary(decimal); // Stores the result from the decimalToBinary function in a variable, called binary. var secondBit = getBit(binary, 1); // Gets the bit in the 1 position (the 2nd bit). The rightmost bit is the 0 position. /* Construct a string message with our results and output the message. */ msg.payload = "decimal: " + decimal + ", binary: " + binary + ", secondBit: " + secondBit; return msg;
-
Click Done. Double-click the Inject node and select number from the drop-down menu. This example uses 3, but you can enter any number that you wish.
- Click Done and Save the flow.
-
Click the button to the left of the Inject node to view the output in the debug tab at the bottom of the flow screen.