~
Inverts all the bits of the number on top: x ~ leaves −x − 1, so 5 ~ gives −6 and 0 ~ gives −1.
Facts
- Word
~- Family
- Bitwise
- Integer stack
- pops 1, pushes 1
- What it does
- Replaces the top with its complement: it flips all 32 bits, so x becomes −x − 1. With an empty stack it leaves −1.
- Cost
- Bitwise command
- Runs
- inside a gene: in the condition (cond) and in the body (start or else)
~ pops a number, flips each of its 32 bits (0s become 1s and 1s become 0s) and pushes the result. In two's complement that is always equivalent to −x − 1:
| Stack before | After ~ |
|---|---|
5 | -6 |
0 | -1 |
-1 | 0 |
4 | -5 |
Its typical use is building a mask to clear a bit with &: 4 ~ has every bit set except the one worth 4, and doing & with the cell leaves everything the same except that bit.
' clears the bit worth 4 in cell 50, leaving the others alone
cond
start
*50 4 ~ & 50 store
stopIf cell 50 held 5 (bits worth 1 and 4), it ends up at 1.
With an empty stack it operates on 0 and leaves −1. The other bit operations are in Bitwise.