# bitwise not - not what I expected

OKB (not okblacke) BrenBarn at aol.com
Sun Aug 17 07:28:17 CEST 2003

```Elaine Jackson wrote:

> Is there a function that takes a number with binary numeral a1...an
> to the number with binary numeral b1...bn, where each bi is 1 if ai
> is 0, and vice versa? (For example, the function's value at 18
> [binary 10010] would be 13 [binary 01101].) I thought this was what
> the tilde operator (~) did, but when I went to try it I found out
> that wasn't the case. I discovered by experiment (and verified by
> looking at the documentation) that the tilde operator takes n to
> -(n+1). I can't imagine what that has to do with binary numerals.
> Can anyone shed some light on that? (In case you're curious, I'm
> writing a script that will play Nim, just as a way of familiarizing
> myself with bitwise operators. Good thing, too: I thought I
> understood them, but apparently I don't.)
>

I think this is because it's also inverting the leading zero bits.
That is, 18 isn't really 10010, it's 000...0010010 with a bunch of 0s
at the front.  (I'm not sure, but I think the number of bits in the
integer type can change with different implementations.)  So when you
bitwise-not it, you get 111...1101101, which is interpreted as -19.

--
--OKB (not okblacke)