tags:

views:

125

answers:

5

I am trying to take one's complement of 0 to get 1 but i get 4294967295. Here is what i have done:

 unsigned int x = 0;
 unsigned int y= ~x;
 cout << y;

My output is 4294967295 but I expect 1, why is this so?. By the way, i am doing this in C++.

+9  A: 

Why do you expect 1? Bit-wise complement flips all the bits.

00000000000000000000000000000000 = 0
              |
          bitwise NOT
              |
              v
11111111111111111111111111111111 = 4294967295

Perhaps you are thinking of a logical NOT. In C++ this is written as !x.

Mark Byers
A: 

An integer is more than just 1 bit (it's 4 bytes, or 32 bits). By notting it, you'r flipping everything, so in this case 00000... becomes 11111...

Alex Zylman
A: 

~ flips all of the bits in the input. Your input is an unsigned int, which has 32 bits, all of which are 0. Flipping each of those 0-bits gives you 32 1-bits instead, which is binary for that large number.

If you only want to flip the least significant bit, you can use y = x ^ 1 - that is, use XOR instead.

Michael Madsen
+3  A: 

Where did you get the expectation of 1 from?

Your understanding of bitwise operations clearly shows is lacking, it would be prudent to work through them first before posting in here...

you're not confusing with a ! which is a logical NOT, are you?

a ~ bitwise complement or a bitwise NOT operation flips all the bits from 1 to 0 and vice versa depending on where in the bitmask is set, so for example, a 1 is

00000000 00000000 00000000 00000001

doing a ~ bitwise NOT on that flips it to

11111111 11111111 11111111 11111110

which gives you the maximum value less 1 of the integer datatype on a 32bit system.

Here is a worthy linky to this which shows you how to do bit-twiddling here.

tommieb75
+2  A: 

You have to look at this in binary to understand exactly what is happening.

unsigned int x = 0, is 00000000 00000000 00000000 00000000 in memory.

The ~x statement flips all bits, meaning the above turns into:

11111111 11111111 11111111 11111111

which converts to 4294967295 in decimal form.

XOR will allow you flip only certain bits. If you only want to flip the least significant bit, use x ^ 1 instead.

Heather