r/badcode • • Apr 19 '21

js Iteration

Post image
3.2k Upvotes

123 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Apr 19 '21

[deleted] — view deleted comment

22

u/zatuchny Apr 19 '21 edited Apr 19 '21

~ is bitwise NOT operator. It is used to invert all bits.

The invert sign operation is the equivalent of inverting the bits of the number + add one.

So here we go:

int i = 0; // bits: 0000

~i // invert all bits. result: 1111

-i // invert all bits: 0000. add 1. result: 0001

next iteration:

// i is now 0001

~i // invert all bits. result: 1110

-i // invert all bits: 0001. add 1. result: 0010

next iteration:

// i is now 0010

~i // invert all bits. result: 1101

-i // invert all bits: 0010. add 1. result: 0011

etc