Rivasa
Rivasa

Reputation: 6740

Replacing “!=” with bitwise operators

using only bitwise operators (|, &, ~, ^, >>, <<), is it possible to replace the != below?

// ...
if(a != b){
    // Some code
}
/// ...

this is mainly out of self interest, since I saw how to do it with == but not !=.

Upvotes: 1

Views: 2500

Answers (6)

nothrow
nothrow

Reputation: 16168

Yes, using this:

if (a ^ b) { }

Upvotes: 0

Ryan Walker
Ryan Walker

Reputation: 844

x ^ y isn't always sufficient. Use !!(x ^ y). Values expecting a one bit return value will not work with x ^ y since it leaves a remainder that could be greater than just 1.

Upvotes: 0

Philip Conrad
Philip Conrad

Reputation: 1499

A bitwise version of the '!=' test could look something like:

if((a - b) | (b - a)) {
    /* code... */
}

which ORs the two subtractions. If the two numbers are the same, the result will be 0. However, if they differ (aka, the '!=' operator) then the result will be 1.

Note: The above snippet will only work with integers (and those integers should probably be unsigned).

If you want to simulate the '==' operator, however, check out Fabian Giesen's answer in Replacing "==" with bitwise operators

Upvotes: 0

binary
binary

Reputation: 13

"~" is equaled to NOT so that should work. example would be "a & ~b".

Upvotes: -2

Jannis Froese
Jannis Froese

Reputation: 1407

if(a ^ b) {
    //some code
}

should work.

You can also use your preferred method for == and add ^ 0xFFFFFFFF behind it (with the right amount of Fs to match the length of the datatype). This negates the value (same as ! in front of it).

Upvotes: 8

Marco Leogrande
Marco Leogrande

Reputation: 8468

a != b means that there is at least one different bit in the bit representations of a and b. The XOR bit operator returns 1 if both input bit operands are different, 0 otherwise.

So, you can apply a XOR operation to a and b and check if the result is not equal to zero.

Upvotes: 3

Related Questions