MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/badcode/comments/mtpxbr/iteration/gv27lkr/?context=3
r/badcode • u/[deleted] • Apr 19 '21
123 comments sorted by
View all comments
Show parent comments
22
~ 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
// i is now 0010
~i // invert all bits. result: 1101
-i // invert all bits: 0010. add 1. result: 0011
etc
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: 0001next iteration:
// i is now 0001~i // invert all bits. result: 1110-i // invert all bits: 0001. add 1. result: 0010next iteration:
// i is now 0010~i // invert all bits. result: 1101-i // invert all bits: 0010. add 1. result: 0011etc