When using the formula below
if ((theFlag div theMask) mod 2) = 0 then
return false
else
return true
end if
I have enum opts (theMask) that are 0 value
Will I have issues with the formula and the
Divide by zero issue?
I guess I should put a safety check in the to test if theMask is zero? And then check if theFlag is also zero?i
0 div or 0 mod anything will be zero, but yes, there will be an error if you try to divide by zero. Depending on what you want the safety checks to do, you could just short-circuit the statement by doing something like return (theMask ≠ 0) and ((theFlag div theMask) mod 2) = 0 - note that you don’t need to use an if statement to return true/false since the comparison already evaluates to a boolean.
The mask is supposed to be an integer to find the value of a specific bit, correct?
Then the code should be this…
if ((theFlag div (2 ^ theMask)) mod 2) = 0 then
return false
else
return true
end if
The bits are numbered starting at zero
This does not work.
Say I have aFlagValue of 9 - 1001
and I want to test if it has the maskOption of 1 - 0001
((9 div (2 ^ 1) ) mod 2)
((9 div 2) mod 2)
(4[.5] mod 2)
(4 mod 2)
[2.]0
final is 0
which your formula returns FALSE which is incorrect
TRY NUMBER 2
Say I have aFlagValue2 of 189 - 1011 1101
test if it has the maskOption of 9 - 1001
((189 div (2 ^ 9) ) mod 2)
((189 div 512) mod 2)
(0[.369140625] mod 2)
(0 mod 2)
[0.]0
final is 0
which returns FALSE again incorrect
The first bit is 0 not 1
So it’s
9 div (2 ^ 0) mod 2
@robertfern’s answer is using the mask for the bit position (which also takes care of the divide by zero). As mentioned, to get the rightmost bit the mask would be 0 instead of 1.
Your original script uses integer division and modulo to get a particular bit, so the mask can’t be zero, which wouldn’t be specifying a bit anyway.
For either answer, the if statement is inverting the logic for using the boolean directly. In that case, you can use not or change the comparison to 1.