Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird output for bitwise NOT

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++.

like image 218
Vaolter Avatar asked Aug 11 '10 19:08

Vaolter


People also ask

What is the Bitwise operator for not?

Bitwise NOT (~) The 32-bit signed integer operand is inverted according to two's complement. That is, the presence of the most significant bit is used to express negative integers. Bitwise NOTing any number x yields -(x + 1) . For example, ~-5 yields 4 .

What is bitwise not of 1?

Bitwise NOT (or complement) is a Bitwise operation, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Bits that are 0 become 1, and those that are 1 become 0. Bitwise NOT is equal to the two's complement of the value minus one.

What is a bitwise negation?

The ~ (bitwise negation) operator yields the bitwise complement of the operand. In the binary representation of the result, every bit has the opposite value of the same bit in the binary representation of the operand.


1 Answers

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.

like image 56
Mark Byers Avatar answered Sep 30 '22 04:09

Mark Byers