Hey all! I got another beginner question. So, I'm learning about bitwise operators from this site. Here's what it says about the bitwise not:
Bitwise NOT is an unary operator that flips the bits of the number i.e., if the ith bit is 0, it will change it to 1 and vice versa. Bitwise NOT is nothing but simply the one’s complement of a number. Lets take an example.
N = 5 = (101)2
~N = ~5 = ~(101)2 = (010)2 = 2
So, ~5 = 2. Now, when I try this in C:
#include <stdio.h>
int main(void) {
int c = 5;
c = ~c;
printf("%d", c);
return 0;
}
The output of the above program is -6. What am I doing wrong?
Videos
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.
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.