~ operator

What does ~ operator do?

Eg. int a =4, ~a???
closed account (1yR4jE8b)
It's the 'complement' operator. It toggles all the bits of whatever you use it with, so 0s become 1s and vice versa.

In your case

a = 4; // 4 is 0100 in binary
a = ~(a) // becomes 1011 in binary which is 11.


EDIT: See my next post for the actual answer.
Last edited on
@darkestfright,
Actually, it doesn't seem to do that:
1
2
3
4
5
6
7
$ python
[..]
>>> a = 4
>>> a
4
>>> ~a
-5

I don't know why it does this - I'd have thought you were right.
chrisname's result is due to the two's complement definition of negative numbers
-n = ~n +1

and darkestfright's example works for 4 bit unsigned integers
Last edited on
closed account (1yR4jE8b)
ah yes, forgot about two's compliment (I rarely use bitwise operations in c++ ever so I forgot about having to do all this stuff initially.).

To addon to/correct my previous post:


a = 4; // 00000000 00000000 00000000 00000100

b = ~a; // 11111111 11111111 11111111 11111011

But b is two's compliment representation of a number. So to know
what it represents, toggle all the bits and add one

so now we have

00000000 00000000 00000000 00000100 + 0001
is
00000000 00000000 00000000 00000101

The left-most significant bit of b (before we toggle and add one), is the sign-bit. If it's 0, the number is positive and negative if 1. In b it is 1.
So b is a negative number. Now, the only significant bits of the toggled+add one value of b is 0101, which is 5 in unsigned binary. So the value of b is -5.
Last edited on
Although Darkestfright explained it pretty well this time, there is still a small minor problem that needs to be highlighted:
~ will, as said, flip ALL bits, when you don't know how many bits you have or what type you are handling, it can be a quite dangerous operator.
Topic archived. No new replies allowed.