Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise operations in Typescript

Reading an article about Angular's change detection mechanism I encountered this typescript code:

detach(): void { this._view.state &= ~ViewState.ChecksEnabled; }

I've been trying to wrap my head around that line of code.

I know the ~ trick and how it's used with indexOf(). I find it hard to understand in terms of bits but remembering that it can be replaced with -(x+1) thus making only -1 falsy makes it easier.

It seems ViewState.ChecksEnabled is a boolean so ~ViewState.ChecksEnabled gives -(0 + 1) or -(1 + 1)

Then with the &= bitwise assignment (?) we get

this._view.state = this._view.state & -1; // or -2

What's the trick here?

https://github.com/angular/angular/blob/6b79ab5abec8b5a4b43d563ce65f032990b3e3bc/packages/core/src/view/view.ts#L346

like image 436
gyc Avatar asked Dec 30 '25 09:12

gyc


1 Answers

I think you should see this as binary calculus.

let's assume the _view.state is equal to 1, and the ViewState.ChecksEnabled is equal to 1.

We have two bitwise operators :

  • & will perform an AND operation on corresponding bits equal to 1
  • ~ will invert the bits

So with the "rewrite" of the operation, we have :

var = 1 & ~ 1

We apply the tilde :

var = 1 & 0

Then the AND :

var = 0

Which would give a plain zero. If you apply this with _view.state equal to 0, that would give :

var = 0 & ~1 = 0 & 0 = 0

When you use 0, 0 :

var = 0 & ~0 = 0 & 1 = 0

And 1, 0 :

var = 1 & ~0 = 1 & 1 = 1

So to sum up :

0, 0 → 0
0, 1 → 0
1, 0 → 1
1, 1 → 0

You can also create a sandbox to test that for several numbers :

for (const i of [0, 1, 2, 3, 4]) {
  for (const j of [0, 1, 2, 3, 4]) {
    console.log(`${i} & ~${j} = ${ i & ~j }`);
  }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!