使用位运算符比较两个整数

编程入门 行业动态 更新时间:2024-10-25 06:33:55
本文介绍了使用位运算符比较两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要使用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.

更多推荐

使用位运算符比较两个整数

本文发布于:2023-11-30 01:36:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648284.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   运算符   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!