But why.

This might seem useless to know, but I have a tendancy to know every inch and probability in all scenarios.

1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main(){
    int a,b;
    a= 33;
    b= ~a;
    std::cout<<b<<"\n";
    std::cin.get();
    return 0;
}


Why does b= ~a come out to -34? Honestly I expected b to be equal to -33 instead of -34. Can any one help me? This might not seem to extravagant but I would appreciate the information on what goes on in the back end of ~
~ inverts all bits. The rest follows from this:
http://en.wikipedia.org/wiki/Two%27s_complement
I don't know a whole lot about the bitwise operators, the ~, NOT, specifically. But what I assume happens is that each int equals a bit somewhere. 0 must exist, and therefor, the opposite of 0 can't be zero, it must be -1. I don't know the bit values of signed ints and therefor I can't specify as to why it works that way. I do know however that it changes all bits in the byte to the opposite.

The definition is:
~ NOT Unary complement (bit inversion)

I already feel like I'm guessing at best, so before I give you completely wrong information, I'll just stop there.

Edit: Athar's link explains it a lot better than I would have...But on the bright side, I would have been close =)

Edit: I crossed it out since it wasn't very helpful overall. And you like not contributing to my posts =P
Last edited on
Is there any reason to make your post hard to read like that, Volatile? Second place is still a place. And look at me, I'm third without even really contributing.
This operation as ~ inverses bits from 1 to 0 and viice-versa from 0 to 1. So if you have for example a value in binary notations as

10100011

you will get

01011100

If to add one to other you will get value that consistts from all 1's

10100011
01011100
======
11111111

When an integer number has all 1s then it is equal to -1.

So you have a + b = -1. And thus b = -a -1 = -33 -1 = -34.
Last edited on
Topic archived. No new replies allowed.