Romit
Romit

Reputation: 77

Dart/Flutter bitwise shift operator returning different values

The bitwise shift operator in Dart/Flutter is returning a different value in web compared to mobile/desktop.

Running the following code:

var checksum = 1150946793;
var shift = checksum << 5;
print(shift);

//Returns the following values
Mobile/Desktop = 36830297376
Web = 2470559008

Is there anything different I am supposed to be doing for the web?

Upvotes: 0

Views: 1583

Answers (2)

Cachapa
Cachapa

Reputation: 1781

To expand on Stephen's answer (which addresses the cause), a solution is to use standard mathematical operators since those aren't truncated to 32-bit:

var checksum = 1150946793;
var shift = checksum * pow(2, 5).toInt();
print(shift);

I'm pretty sure this is orders of magnitude slower than using bitwise operations so it might be wise to use it only where you absolutely need to handle 64-bit values (as in my case with µs-precision timestamps).

Upvotes: 1

Stephen
Stephen

Reputation: 4249

Dart stores integers as a signed 64-bit value giving them a possible range of −(2^63) to 2^63 − 1. When the maximum value of an integer is exceeded, wrap around occurs and the most significant bits are lost.

However with complied JavaScript the bitwise operators truncate their operands to 32-bit integers. This means you are seeing wrap around at a much lower value (4294967296) than you will on desktop or mobile. This is why your numbers are computing differently.

The docs for int have a note that covers this.

Upvotes: 2

Related Questions