function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan SpinkJonathan 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?
SwethaSwetha (Salesforce Developers) 
The error message you are seeing is because you are trying to assign an integer value to a boolean variable. To check if a particular bit is set in an integer, you can use the bitwise AND operator (&) with a bit mask.

Example:
Integer x = 9; // 1001 in binary
Boolean isBitSet = (x & 8) != 0; // check if the 4th bit is set
System.debug(isBitSet); // output: true

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