Search code examples
binarybit-manipulationbitwise-operatorsgml

How does the binary NOT (~) operator work?


I am quite new to programming and i have been trying to learn some basic binary, but there is still one thing that i don't quite understand. It's the rules regarding the NOT operator.

lets say i wan't to calculate this: 62&~29

62 = 111110
29 = 011101

now the result as far as i understand should be this:

100011 = 35

but the result i get from the code is 34.

So my question is: what is happening with the last value? Why is it not being added to 34?

Hope someone can explain it to me :D

Have a nice day.


Solution

  • ~ is not the not operator, it is the bitwise complement operator.

    It takes the bit pattern of the operand, and converts all 0 bits to 1 bits and all 1 bits to 0 bits.

    The effect it has on a numeric value will depend on the complement convention that your implementation uses, and the number of bits used to represent that type.

    In your specific example, 62&~29 is evaluated as 62&(~29) which is 111110&(~011101) which is 111110&a100010 which is 100010 which is 34. Here I'm being pedantic and am using a to stand in for a number of 1 bits, so the number of bits equals the width of your type.