0

So I am running dart on DartPad And I tried running the following code:

import 'dart:math';

void main() {
  print(~0);
  print(~-1);
  print(~~-1);
}

Which resulted in the following outputs

4294967295
0
4294967295

As you can see inverting the bits from 0 results in the max number (I was expecting -1 as dart uses two's complement) and inverting from -1 results in 0, which creates the situation where inverting 2 times -1 does not give me -1.

Looks like it's ignoring the first bit when inverting 0, why is that?

My Car
  • 4,198
  • 5
  • 17
  • 50
Seiji Hirao
  • 310
  • 2
  • 16
  • 3
    Might just be a DartPad thing. Here's another Dart interpreter's output: [Try it online!](https://tio.run/##S0ksKvn/vyw/M0UhNzEzT0NToZpLQaGgKDOvRKPOQNMawdE1ROZBuLX//wMA "Dart – Try It Online") – General Grievance Jan 27 '22 at 18:15
  • In fact, numbers in DartPad seem broken in general? I don't really know Dart too well, but `9007199254740991 + 2` should give `9007199254740993` because it should represent 64-bit integers, but in DartPad it gives `9007199254740992` which is what JS would do with its limited precision. – General Grievance Jan 27 '22 at 18:39
  • 1
    The problem is that DartPad runs your code as compiled JavaScript and JavaScript represent all numbers as the type `double`. You can read more here: https://stackoverflow.com/questions/70741250/a-dart-code-behaves-differently-in-dartpad-and-local-because-of-double-type – julemand101 Jan 27 '22 at 18:44
  • Does this answer your question? [A dart code behaves differently in dartpad and local because of double type](https://stackoverflow.com/questions/70741250/a-dart-code-behaves-differently-in-dartpad-and-local-because-of-double-type) – General Grievance Jan 27 '22 at 18:58
  • 3
    If you want 32- or 64-bit numbers that are portable across the Dart VM and Dart for the Web, you can use [`package:fixnum`](https://pub.dev/packages/fixnum), although that will sacrifice some speed. – jamesdlin Jan 27 '22 at 20:03
  • @julemand101 I understood that the number is represented as a double, but shouldn't this behavior still be weird with doubles? Because inside js I can run `~~-1` and still get `-1`. Or is this a problem when dart interprets the double as a int? – Seiji Hirao Jan 28 '22 at 01:05
  • @Calculuswhiz So the interpreter you sent isn't compiling to js? Or is it really a DartPad problem and not a problem from compiling to js? – Seiji Hirao Jan 28 '22 at 01:08

1 Answers1

3

Dart compiled for the web (which includes DartPad) uses JavaScript numbers and number operations. One of the consequences of that is that bitwise operations (~, &, |, ^, <<, >> and >>> on int) only gives 32-bit results, because that's what the corresponding JavaScript operations do.

For historical reasons, Dart chooses to give unsigned 32-bit results, not two's complement numbers. So ~-1 is 0 and ~0 is the unsigned 0xFFFFFFFF, not -1.

In short, that's just how it is.

lrn
  • 64,680
  • 7
  • 105
  • 121