You need to sign in to do that
Don't have an account?
Jonathan Spink
Can you use a bit wise operator on integer variables?
I'm coding a set of true/false opions by setting an integer field x to say 9 (1001 in binary), so that if I want to check if any particular bit is set, I do:
x & 8 (= true), or
x & 2 (= false), etc.
But the compiler complains, saying 'Illegal assignment from Integer to Boolean' having also said '& operator can only be applied to Boolean expressions or to Integer or Long expressions'. Hoow can I get this basic functionality to work?
x & 8 (= true), or
x & 2 (= false), etc.
But the compiler complains, saying 'Illegal assignment from Integer to Boolean' having also said '& operator can only be applied to Boolean expressions or to Integer or Long expressions'. Hoow can I get this basic functionality to work?
Example:
In the above example, we are checking if the 4th bit (from the right) is set in the integer variable x. The bit mask 8 is 1000 in binary, which means it has a 1 in the 4th bit position and 0s in all other positions. When we perform the bitwise AND operation between x and 8, we get 8, which means the 4th bit is set. We then compare the result with 0 to convert it to a boolean value.
You can use a similar approach to check other bits in the integer variable x
Related:
https://salesforce.stackexchange.com/questions/332843/bitwise-operators-usage
https://blog.deadlypenguin.com/2015/02/17/bitwise-operations-apex/
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm
https://youtu.be/3mhvJJzAQIQ
Thanks