Issue
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..
Solution
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.
Answered By - Peter Lawrey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.