用C进行按位运算以比较两个整数 [英] Bitwise operation in C to compare two integers

查看:64
本文介绍了用C进行按位运算以比较两个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在一个班上接受了测验.问题如下:

I was recently given a quiz in one of my classes. The question is below:

在C语言中编写一个函数(称为cmp),该函数接受两个整数(xy) 并返回:-1如果x< y,如果x = y,则为0,如果x> y,则为1.尽可能简洁地写cmp.

Write a function (called cmp) in C that accepts two integers (x and y) and returns: -1 if x < y, 0 if x = y, 1 if x > y. Write cmp as concise as possible.

我能想到的最简洁的功能是:

The most concise function that I could think of was:

int cmp(int x, int y) {
    return ((x < y) ? (-1) : ((x == y) ? (0) : (1)));
}

但是我感觉可能会有一些操纵,我可以使用它来更简洁地做到这一点.也许&^的组合?在过去的几天里,这一直困扰着我,我想知道实际上是否有 IS 做到这一点的更好方法?

But I have a feeling there could be a bit manipulation that I could use to do this more concisely. Perhaps a combination of & and ^ ? This has been bothering me for the last few days and I wanted to know if there in fact IS a better way to do this?

推荐答案

尽可能简洁"是对测验的一个非常模糊的要求.您是否希望打高尔夫球?是否删除空格和括号使其更简洁?无论如何,这是一种对比较结果进行算术运算的解决方案:

"as concise as possible" is an extremely vague requirement for a quiz. Are you expected to do code golf? Does removing whitespace and parentheses make it more concise? Anyway, here’s one solution using arithmetic on the results of comparisons:

int cmp(int x, int y) {
    return (x > y) - (x < y);
}

这篇关于用C进行按位运算以比较两个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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