使用位运算符比较两个整数 [英] Compare two integers using bit operator
问题描述
我需要使用Bit运算符比较两个整数。
我遇到了一个问题,我必须比较两个整数而不使用比较运算符。使用位运算符会有所帮助。但是如何?
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?
让我们说
a = 4;
b = 5;
Lets say a = 4; b = 5;
我们必须显示a不等于b。
但是,我想进一步扩展它,比方说,我们将显示哪个更大。这里b更大..
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..
推荐答案
至少需要与0进行比较,从概念上讲,这就是CPU所做的比较。例如
You need at least comparison to 0 and notionally this is what the CPU does for a comparison. e.g.
等于可以建模为 ^
,因为这些位必须相同才能返回0
Equals can be modelled as ^
as the bits have to be the same to return 0
(a ^ b) == 0
如果这是 C
你可以放弃 == 0
,因为这可以隐含
if this was C
you could drop the == 0
as this can be implied with
!(a ^ b)
但是在Java中你不能将 int
转换为 boolean
而不是至少一些比较。
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
减法与添加负数相同且负数与~x + 1相同所以你可以做
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
放弃 +1
你可以将此更改为
(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.
这篇关于使用位运算符比较两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!