How do I perform bitwise unsigned right shift / zero-fill right shift in Dart?
Something like this for instance:
foo >>> 2
The unsigned right shift operator ( >>> ) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand.
Bitwise Zero Fill Right Shift Operator shifts the bits of the number towards the right a specified n number of positions. The sign bit filled with 0's. The symbol >>> represents the Bitwise Zero Fill Right Shift Operator. When we apply >>> on a positive number, it gives the same output as that of >>.
Zero-fill right shift (>>>) operator: The operator shifts the bits of the first operand by a number of bits specified by the second operand. The bits are shifted to the right and those excess bits are discarded, while 0 bit is added from left.
The signed right shift operator '>>' uses the sign bit to fill the trailing positions. For example, if the number is positive then 0 will be used to fill the trailing positions and if the number is negative then 1 will be used to fill the trailing positions. In Java, negative numbers are stored as 2's complement.
Zero-fill right shift requires a specific integer size. Since integers in Dart are of arbitrary precision the '>>>' operator doesn't make sense there.
The easiest way to emulate a zero-fill right shift is to bit-and the number first.
Example:
(foo & 0xFFFF) >> 2 // 16 bit zero-fill shift
(foo & 0xFFFFFFFF) >> 2 // 32 bit shift.
Dart integers are now 64 bit. Since Dart 2.14 the >>>
operator shifts the 64 bit integer and fills the most significant bits with 0.
The triple-shift operator, i.e. bitwise unsigned right shift of integers has now been added as of Dart 2.14.
>>>
operator in DartYou can simply use this starting with Dart version 2.14:
var foo = 42;
foo >>> 2;
In order to enable this for your app by default, you must upgrade your SDK constraint in pubspec.yaml
:
environment:
sdk: '>=2.14.0-0 <3.0.0'
Learn more about the operator in the docs.
If you have not yet upgraded to Dart 2.14, you can simply use this function:
/// Bitwise unsigned right shift of [x] by [s] bits.
///
/// This function works as `>>>` does starting with Dart 2.14.
int urs(int x, int s) => s <= 0 ? x : (x >> s) & (0x7fffffffffffffff >> (s - 1));
This works because integers are always 64-bit in Dart nowadays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With