Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bit-wise operation unary ~ (invert)

I'm a little confused by the ~ operator. Code goes below:

a = 1 ~a  #-2 b = 15 ~b  #-16 

How does ~ do work?

I thought, ~a would be something like:

0001 = a 1110 = ~a  

why not?

like image 464
Alcott Avatar asked Sep 02 '11 02:09

Alcott


People also ask

What is a bitwise invert?

The bitwise NOT operator ( ~ ) inverts the bits of its operand. Like other bitwise operators, it converts the operand to a 32-bit signed integer.

Is bitwise exclusive or unary operator?

The bitwise operator not is a unary operator that has only a right operand.

How do you invert all bits?

Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number.

Which bitwise operator is used for flipping bits?

Binary One's Complement Operator is unary and has the effect of 'flipping' bits.


1 Answers

You are exactly right. It's an artifact of two's complement integer representation.

In 16 bits, 1 is represented as 0000 0000 0000 0001. Inverted, you get 1111 1111 1111 1110, which is -2. Similarly, 15 is 0000 0000 0000 1111. Inverted, you get 1111 1111 1111 0000, which is -16.

In general, ~n = -n - 1

like image 129
NullUserException Avatar answered Oct 03 '22 00:10

NullUserException