Tower
Tower

Reputation: 102905

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

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

Answers (3)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126834

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.

Upvotes: 5

Florian Loitsch
Florian Loitsch

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.

Update 2021:

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

Kai Sellgren
Kai Sellgren

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

Related Questions