3

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.

user2314737
  • 27,088
  • 20
  • 102
  • 114

2 Answers2

3

~ 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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1
29    --> 011101
not29 --> 100010 (turn 1s into 0 and vice-versa)

62       --> 111110
not29    --> 100010
62&not29 --> 100010 (1 if and only if both are 1, otherwise 0)

How did you get 35?

user2314737
  • 27,088
  • 20
  • 102
  • 114
  • I got 35 because i didn't really know how the & works, but i see now what i got wrong. I converted 0 to 1 even though both wasn't ones or zeroes. Thanks for the help :) – Captain Leaf Blower Nov 25 '16 at 09:58