Working with bit values of numerical variables
Example of how to get or set the value of a specific bit from a number variable
Examples are valid for:
CB2 Software version: 1.8.16941
CB3 Software version: 3.1.17779
e-Series Software version: All versions
Note that older or newer software versions may behave differently.
First we are going to define a function that will perform the calculations needed to get a bit individually from a numerical value. We can have the function defined in a script file Bit_Functions.script, and it could be like:
def getBitValueFromInt(intVal, bitNumber): a = 1 i = 1 while (i < bitNumber) : i=i+1 a = a * 2 end b = floor(intVal / a) return ((b/2) != floor(b/2)) end |
This script file can be generated using your preferred text editor
To use this function from a robot program, do the following:
1: Call the script file Bit_Functions.script in the BeforeStart Sequence
2: On the Robot Program, create a variable which is the one to mask a bit from, e.g.:
var_1 = 50
3: Make an assignment to a new variable which will be given the value returned by the function we have defined. The parameters of the function are the variable from step 2, and the index of the bit you want to mask out. (The least significant bit has index 1). e.g.:
var_2 = getBitValueFromInt(var_1,5)
After running the program var_2 will have the bit value of the bit with index 5 from var_1. In the example, var_2 will be TRUE. This is because the bit pattern of 50 is 0011 0010.
Find the program example1.urp file at the bottom of the page (SW3.1)
If instead you want to set a specific bit of a number variable, you may add a function like this in the script file:
def getIntWithBitSet(originalIntVal, bitNumber, bitValue) : a = 1 i = 1 while (i < bitNumber) : i=i+1 a = a * 2 end b = floor(originalIntVal / a) c = originalIntVal if ((b/2) == floor(b/2)) : if (bitValue == True) : c = c + a end else : if (bitValue == False) : c = c - a end end return c end |
We can now use this function as we did with the previous; in the following example the returned value on var_2 is now 1002:
Find the program example2.urp file at the bottom of the page (SW3.1)
Find the script file here. Attached as Bit_Functions.script