简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM