Dart Bitwise Operators
Bitwise operators in Dart are used to perform operations on individual bits of integer values. These operators are useful in low-level programming tasks, such as manipulating binary data, optimizing performance, or implementing specific algorithms that require bitwise calculations. Dart provides several bitwise operators, which can be applied to integers (int
type).
Overview of Bitwise Operators
- Bitwise AND (
&
) - Bitwise OR (
|
) - Bitwise XOR (
^
) - Bitwise NOT (
~
) - Left Shift (
<<
) - Right Shift (
>>
) - Unsigned Right Shift (
>>>
)
1. Bitwise AND (&
)
Description: The bitwise AND operator compares each bit of two integers and returns a new integer where each bit is set to
1
if both corresponding bits of the operands are1
, otherwise it is set to0
.Example:
2. Bitwise OR (|
)
Description: The bitwise OR operator compares each bit of two integers and returns a new integer where each bit is set to
1
if at least one of the corresponding bits of the operands is1
.Example:
3. Bitwise XOR (^
)
Description: The bitwise XOR (exclusive OR) operator compares each bit of two integers and returns a new integer where each bit is set to
1
if only one of the corresponding bits of the operands is1
(i.e., they are different).Example:
4. Bitwise NOT (~
)
Description: The bitwise NOT operator inverts the bits of an integer, changing
1
bits to0
and0
bits to1
.Example:
5. Left Shift (<<
)
Description: The left shift operator shifts the bits of an integer to the left by a specified number of positions. It fills the rightmost bits with
0
.Example:
6. Right Shift (>>
)
Description: The right shift operator shifts the bits of an integer to the right by a specified number of positions. For signed integers, it preserves the sign bit (arithmetic shift).
Example:
7. Unsigned Right Shift (>>>
)
Description: The unsigned right shift operator shifts the bits of an integer to the right by a specified number of positions, filling the leftmost bits with
0
, regardless of the sign.Example:
Summary of Bitwise Operators
Operator | Description | Example |
---|---|---|
& | Bitwise AND | 5 & 3 (results in 1 ) |
` | ` | Bitwise OR |
^ | Bitwise XOR | 5 ^ 3 (results in 6 ) |
~ | Bitwise NOT | ~5 (results in -6 ) |
<< | Left Shift | 5 << 1 (results in 10 ) |
>> | Right Shift | 5 >> 1 (results in 2 ) |
>>> | Unsigned Right Shift | -8 >>> 1 (results in a positive integer) |
Conclusion
Bitwise operators in Dart provide a powerful way to manipulate individual bits of integers. These operators can be extremely useful in low-level programming tasks, including performance optimization and data manipulation. Understanding how to use bitwise operators effectively is important for developers who work with binary data or require efficient algorithms.