用算术/按位运算符实现关系运算符 [英] Implement relational operator with arithmetic/bitwise operators

查看:137
本文介绍了用算术/按位运算符实现关系运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

  • 以二进制补码形式的32位有符号整数
  • truefalse是具有值10
  • 的整数
  • java运算符
  • 32-bit signed integers in two's complement form
  • true and false are integers with values 1 and 0
  • java operators

您可以仅使用算术和按位运算符来实现像<==这样的关系运算符吗?

Can you implement relational operators like < and == using only arithmetic and bitwise operators?

推荐答案

这里是一种快速尝试.小于号是比较麻烦的,但是如果需要,可以在32位算术中使用.

Here's a quick attempt. Signed less-than is messy but possible in 32-bit arithmetic if needed.

int32_t cmp_lt(int32_t lhs, int32_t rhs) {
    int64_t tmp = lhs;
    tmp -= rhs;
    tmp >>= 63;
    return tmp & 1;
}

int32_t cmp_eq(int32_t lhs, int32_t rhs) {
    return (cmp_lt(lhs, rhs) | cmp_lt(rhs, lhs)) ^ 1;
}

// 32-bit only version
int32_t cmp_lt32(int32_t lhs, int32_t rhs) {
    int32_t tmp = lhs - rhs;
    // -lhs < +rhs is always true
    tmp |= ~rhs & lhs;
    // +lhs < -rhs is always false
    tmp &= ~rhs | lhs;
    tmp >>= 31;
    return tmp & 1;
}

edit:我看到有人要求使用Java.不是我的母语,但我相信这里可以用int32_t和int64_t替换常规整数和long类型.

edit: I see that Java was asked for. Not my native language but I believe the regular integer and long types could be substituted for int32_t and int64_t here.

这篇关于用算术/按位运算符实现关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆