Reputation: 102905
How do I perform bitwise unsigned right shift / zero-fill right shift in Dart?
Something like this for instance:
foo >>> 2
Upvotes: 9
Views: 3757
Reputation: 126834
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.
Upvotes: 5
Reputation: 8128
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.
Upvotes: 12
Reputation: 30272
You could define a utility function to use:
int zeroFillRightShift(int n, int amount) {
return (n & 0xffffffff) >> amount;
}
That assumes you have 32-bit unsigned integers and that's ok if you do have.
Upvotes: 2