Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two integers using bit operator

Tags:

java

integer

I need to compare two integer using Bit operator. I faced a problem where I have to compare two integers without using comparison operator.Using bit operator would help.But how?

Lets say a = 4; b = 5;

We have to show a is not equal to b. But,I would like to extend it further ,say,we will show which is greater.Here b is greater..

like image 922
Zahid Hossain Avatar asked Jul 28 '15 13:07

Zahid Hossain


People also ask

How do you compare bit and bit?

Here's the process to OR two binary numbers together: line up each number so the bits match up, then compare each of their bits that share a position. For each bit comparison, if either or both bits are 1, the value of the result at that bit-position is 1.

How do you compare bits in C++?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.

How do you compare two numbers without using a comparison operator?

Another Approach is using “-” (Minus/Subtraction Operator). If the Result of Subtraction between the two Numbers is “Zero”, then they are equal (we return '1'), else they are not equal (we return '0').

What does the & bit operator do?

The bitwise AND operator ( & ) compares each bit of the first operand to the corresponding bit of the second operand. If both bits are 1, the corresponding result bit is set to 1. Otherwise, the corresponding result bit is set to 0.


2 Answers

Using binary two’s complement notation

int findMax( int x, int y)
{
 int z = x - y;
 int i  = (z  >>  31)  &  0x1;
 int  max  =  x - i  *  z;
 return max;
}

Reference: Here

like image 154
rhitz Avatar answered Oct 02 '22 04:10

rhitz


You need at least comparison to 0 and notionally this is what the CPU does for a comparison. e.g.

Equals can be modelled as ^ as the bits have to be the same to return 0

(a ^ b) == 0

if this was C you could drop the == 0 as this can be implied with

!(a ^ b)

but in Java you can't convert an int to a boolean without at least some comparison.

For comparison you usually do a subtraction, though one which handles overflows.

(long) a - b > 0 // same as a > b

subtraction is the same as adding a negative and negative is the same as ~x+1 so you can do

(long) a + ~ (long) b + 1 > 0

to drop the +1 you can change this to

(long) a + ~ (long) b >= 0 // same as a > b

You could implement + as a series of bit by bit operations with >> << & | and ^ but I wouldn't inflict that on you.

like image 24
Peter Lawrey Avatar answered Oct 02 '22 03:10

Peter Lawrey