How to do bitwise unsigned (zero-fill) right shift in Dart?

Viewed 2663

How do I perform bitwise unsigned right shift / zero-fill right shift in Dart?

Something like this for instance:

foo >>> 2
3 Answers

The triple-shift operator, i.e. bitwise unsigned right shift of integers has now been added as of Dart 2.14.

Triple-shift >>> operator in Dart

You 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.

Pre Dart 2.14

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.

Related