Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation of Bitwise NOT Operator

Why is it that the bitwise NOT operator (~ in most languages) converts the following values like so:

-2 -> 1
-1 -> 0
0 -> -1
1 -> -2

Shouldn't -2 convert to 2, 1 convert to -1, etc.?

like image 687
Maxpm Avatar asked Nov 28 '10 05:11

Maxpm


People also ask

What is Bitwise Not operator?

The bitwise NOT operator in C++ is the tilde character ~ . Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.

What is Bitwise not of 1?

Overview# 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.

How does Bitwise NOT operator work in Java?

Bitwise Not or Complement operator simply means the negation of each bit of the input value. It takes only one integer and it's equivalent to the ! operator. This operator changes each binary digit of the integer, which means all 0 become 1 and all 1 become 0.


3 Answers

See two's complement for the representation of negative integers in many languages. As you can see, -2 is represented by 1111110; if you invert all those bits you get 0000001, i.e. a value of 1.

like image 189
Phrogz Avatar answered Sep 29 '22 10:09

Phrogz


It helps if you look at it in binary.

First of all, as you know, negative numbers are expressed as (highest possible unsigned number plus 1 minus value). So -1 in a 16-bit integer, which has the highest unsigned value of 65535, would be 65536-1=65535, i.e. 0xffff in hex, or 1111 1111 1111 1111 in binary.

So:

1 in binary = 0000 0000 0000 0001

NOT on all bits would result in 1111 1111 1111 1110. That, in decimal, is 65534. And 65536 minus 65534 is 2, so this is -2.

like image 21
EboMike Avatar answered Sep 29 '22 09:09

EboMike


Most (all?) modern architectures use two's complement to represent signed integers. The bitwise NOT is thus the complement of the integer minus one.

like image 40
user505255 Avatar answered Sep 29 '22 08:09

user505255