Previous section To contents Next section

5.4 Bitwise/set operators

These operators are used to manipulate bits as members in sets. They can also manipulate arrays, multisets and mappings as sets.

Function Syntax Identifier Returns
Shift left a << b `<< Multiplies a by 2 b times.
Shift right a >> b `>> Divides a by 2 b times.
Inverse (not) ~ a `~ Returns -1-a.
Intersection (and) a & b `& All elements present in both a and b.
Union (or) a | b `| All elements present in a or b.
Symmetric difference (xor) a ^ b `^ All elements present in a or b, but not present in both.

The first three operators can only be used with integers and should be pretty obvious. The other three, intersection, union and symmetric difference, can be used with integers, arrays, multisets and mappings. When used with integers, these operators considers each bit in the integer a separate element. If you do not know about how bits in integers work I suggest you go look it up in some other programming book or just don't use these operators on integers.

When intersection, union or symmetric difference is used on an array each element in the array is considered by itself. So intersecting two arrays will result in an array with all elements that are present in both arrays. Example: ({7,6,4,3,2,1}) & ({1, 23, 5, 4, 7}) will return ({7,4,1}). The order of the elements in the returned array will always be taken from the left array. Elements in multisets are treated the same as elements in arrays. When doing a set operation on a mapping however, only the indices are considered. The values are just copied with the indices. If a particular index is present in both the right and left argument to a set operator, the one from the right side will be used. Example: ([1:2]) | ([1:3]) will return ([1:3]).


Previous section To contents Next section