Question

Hello I have been trying to do my homework in my Machine Organisation class. I had to write code

/*    
 *   Examples: isNotEqual(5,5) = 0, isNotEqual(4,5) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 6
 *   Rating: 2
 */

after some thinking I realized to write code

int isNotEqual(int x, int y) {
  return x^y;
}

but it didn't work. after some searching I found a code that was similar to mine, but had !! in front of x^y.

int isNotEqual(int x, int y) {
  return !!(x^y);
}

After finding this code I tried it and it worked. So I tried the same thing but with ~~ in front, but it didn't work. As I understand ! means not only "not " but it also does something else. Which is why we did !! (not+not=yes) twice to get the same value, but a different answer.

Am I correct about !!? What does ! exactly do? What is the difference between ~ and !? When is the appropriate time to use ~ and when is the appropriate time to use !?

Was it helpful?

Solution

~ flips all the bits in a number. Flipping every bit twice, gives you back the same bits, so the number stays the same.

! gives you zero when applied to a non-zero operand and one when applied to zero. So if the operand is one or zero, it will give you back the same operand. But when the operand is neither one nor zero, it will give you back one instead of the original number.

So ~~ always gives you the original number and !! gives you one or zero.

OTHER TIPS

! is using to get the opposite of a thing.

Opposite of true is false Opposite of false is true

~ is using to change all bit by it opposite.

Opposite of false is true (1111 1111 ... is not equals to zero) Opposite of true is not false (0000 0001 -> 1111 1110 not equals to zero so true and not false)

Use ! for logical proposal and ~ for binary operations.

The first you understand is that the xor operator x^y is the bit-manipulation operator that returns 0 only if the two bits are equal i.e, 1^1 and 0^0 is 0, while 1^0 and 0^1 is 1. So x^y is zero if all the bits of x and y are equal, non-zero otherwise.

The use of !! is that, a single ! returns an integer value of either 0 or 1, and a double !! returns the opposite of the previous result. If you think about it, that means, !! on a zero operand returns 0, while !! on a non-zero operand returns 1, exactly wha t you need.

~ is the bit-not operator, double ~~ returns the original number, it doesn't return only 0 or 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top