I've been trying to figure out bitwise operators again today, and some things are still a little fuzzy to me. Everything made sense until I started trying to combine the | operator with ~, for instance: number | ~number
. On a side note, I already read the wikipedia article on the two's complement, and understand that aspect of it (I think).
------------------------------------------
| 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 |
------------------------------------------
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | = 7
------------------------------------------
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | = ~5 or -6
------------------------------------------
Using the & operator like 7 & ~5
yields the expected result of 2, as only the 2 column is set in both rows. What's getting me here is that 7 | ~5
is outputting -1. I'd expect that would either be 255, because every column has a 1 in it, or 5, because the bottom row might count 0s instead of 1s. But it's neither of those, it's -1.
I've googled this until my brain hurts, and I can't find one single article anywhere that addresses this. Does anyone know what's going on here?