Sub topic 20
Bitwise operators
Bitwise operators work on the individual binary digits (bits) of an integer value. They are the least used operators in Apex. They matter mainly when you read compact flag fields, pack several yes/no values into one number, or maintain code that does.
This chapter assumes you know how Integer and Long differ (see the numeric types chapter) and how operator precedence groups expressions. It also assumes you can count in binary.
What bitwise operators do
An Apex Integer is a 32-bit signed value. A Long is a 64-bit signed value. A bitwise operator compares or moves the bits of its operands position by position and returns a new number.
| Operator | Name | Result for each bit position | Column |
|---|---|---|---|
| `&` | AND | 1 only if both bits are 1 | |
| `\ | ` | OR | 1 if either bit is 1 |
| `^` | Exclusive OR (XOR) | 1 if the bits differ | |
| `<<` | Shift left | Moves bits left, filling with 0 | |
| `>>` | Signed shift right | Moves bits right, keeping the sign bit | |
| `>>>` | Unsigned shift right | Moves bits right, filling with 0 |
Each operator has a compound assignment form: &=, |=, ^=, <<=, >>=, and >>>=. These work like +=. The expression x |= y means x = x | y.
Apex has no ~ (bitwise NOT) operator. When you need to invert bits, XOR with -1. In two's complement, -1 has every bit set to 1, so x ^ -1 flips every bit of x.
The operands must be integral types, meaning Integer or Long. Double and Decimal values are not valid operands. Convert them first, and note that conversion discards the fraction.
AND, OR, and XOR on small numbers
Take 5 (binary 101) and 3 (binary 011).
Integer a = 5; // 101
Integer b = 3; // 011
System.debug(a & b); // 001 -> 1
System.debug(a | b); // 111 -> 7
System.debug(a ^ b); // 110 -> 6
System.debug(a ^ -1); // flips every bit -> -6Reading column by column:
&keeps only the bits set in both numbers. Only the rightmost bit is set in both, so the result is1.|keeps bits set in either number, which gives111.^keeps bits that differ, which gives110.
The last line shows the NOT workaround. Flipping every bit of a two's complement number x produces -x - 1, so 5 ^ -1 is -6.
Shifts
A left shift by n positions multiplies by 2 to the power n, as long as the result fits in the type. A signed right shift divides by 2 to the power n and rounds toward negative infinity.
Integer value = 12; // 1100
System.debug(value << 2); // 110000 -> 48
System.debug(value >> 2); // 11 -> 3
System.debug(-8 >> 1); // sign preserved -> -4
Long big = 1L << 40;
System.debug(big); // 1099511627776The difference between >> and >>> shows up only with negative numbers. >> copies the sign bit into the vacated positions, so a negative number stays negative. >>> fills with zeros, so the result of a negative value becomes a large positive one. For non-negative numbers the two behave the same.
Shifts can overflow. An Integer holds 32 bits, so a flag at bit 40 does not fit. Use Long and the L suffix on literals (1L << 40). Without the suffix, the literal is an Integer.
Bit flags: the main practical use
A bit flag stores one yes/no fact in one bit. Several flags then share one integer. Give each flag a distinct power of two:
final Integer READ = 1; // 001
final Integer WRITE = 2; // 010
final Integer EXEC = 4; // 100
Integer perms = 0;
perms |= READ; // set a flag
perms |= WRITE;
System.debug(perms); // 3
Boolean canWrite = (perms & WRITE) != 0; // test a flag
System.debug(canWrite); // true
perms &= (WRITE ^ -1); // clear a flag
System.debug(perms); // 1
perms ^= EXEC; // toggle a flag
System.debug(perms); // 5The four patterns are always the same:
- Set a flag with
value |= flag. - Test a flag with
(value & flag) != 0. - Clear a flag with
value &= (flag ^ -1). - Toggle a flag with
value ^= flag.
Checking even and odd
The lowest bit of an integer is 1 for odd numbers and 0 for even numbers, so & 1 works as a parity test. Note the parentheses:
Integer n = 6;
Boolean isEven = (n & 1) == 0;
System.debug(isEven); // trueCommon errors
Missing parentheses
Bitwise operators rank below comparison and equality operators in the precedence order. Without parentheses, n & 1 == 0 groups as n & (1 == 0). That compares an Integer with a Boolean and does not compile. Always wrap the bitwise part: (n & 1) == 0.
Mixing `&` with `&&`
&& and || are logical operators on Booleans and short-circuit. & and | on integers are bitwise and always evaluate both sides. Typing & where you meant && on integer operands gives a numeric result where a condition is expected, and the compiler rejects it in an if.
Using non-integral values
Decimal and Double cannot be shifted or masked. A currency value such as 19.99 has no meaningful bit pattern for this purpose.
Overflow on Integer
A flag value above 2^30 (or 1 << 31, which is negative) can surprise you, and flags beyond bit 31 do not exist in an Integer. Store wider flag sets in a Long, or use a different structure.
When not to use bit flags
Bit flags are compact but hard to read and hard to query. In Salesforce, other choices are usually clearer:
- A
Set<String>orSet<Enum>holds named options and supportscontains. - A multi-select picklist stores several values and supports
INCLUDESin SOQL. - Separate Boolean fields can be filtered and reported on directly.
Choose bit flags when you must match an existing numeric format, such as a code from an external system, or when you pass many flags through a single integer parameter. Document each flag constant by name, as in the example above, so readers never see bare numbers like perms & 4.
Exercise
Given Integer x = 6 (binary 110) and Integer y = 3 (binary 011), what do x & y, x | y, and x ^ y return?
Show answer
x & y is 2 (010), x | y is 7 (111), and x ^ y is 5 (101).
Exercise
Using the READ = 1, WRITE = 2, EXEC = 4 constants, write an expression that is true when the Integer perms has the EXEC flag set. Why are the parentheses needed?
Show answer
(perms & EXEC) != 0. Bitwise & ranks below comparison operators, so without the parentheses the expression groups as perms & (EXEC != 0), which compares an Integer with a Boolean and does not compile.