int y = 2, x = 3, z = 1, k; k = y&~z; 

How is the value of 2 ? How do these operations work &~ ?

  • Why is x here? - AnT

1 answer 1

The value of y is 2 , which in binary representation is expressed by the bit set 00..010 .

The value of z is 1 , which in binary representation is expressed by the bit set 00..001 .

Applying a bit inversion operation ~ to the value of z gives a bit set of 11..110 .

Then the bitwise AND operator & is applied to the binary representations of y and ~z , i.e. by 00..010 and 11..110 respectively, which results in a binary representation of 00..010 .

And this is a binary representation of the same 2 .


Separately, it is worth noting that bitwise manipulations are best performed with unsigned types, unless there is a special need to use signed types.

  • spasibo ponial vso :) - Beso Poladishvili