仅使用位运算符在C中对符号函数进行签名 [英] sign function in C using bit operators only

查看:164
本文介绍了仅使用位运算符在C中对符号函数进行签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用按位运算符来实现符号函数.我知道,如果我只想提取带符号整数的符号位,则可以执行:(x >> 31) & 1.

I'm trying to implement a sign function using only bitwise operators. I know that if I just want to extract the sign bit of a signed integer, I can do: (x >> 31) & 1.

此外,我知道条件可以写为布尔表达式:

Also, I understand that conditionals can be written as boolean expressions:

if(x) a=y else a=z可以重写为:

a=( (x<<31) << 31 ) & y + ( !x << 31) >> 31) & z,假设x = 1或0.

a=( (x<<31) << 31 ) & y + ( !x << 31) >> 31) & z, assuming x=1 or 0.

这个问题有点棘手,因为我有3个条件情况:
如果为正,则返回1;如果为零,则返回0;如果为负,则返回-1.

This problem gets a little tricky though because I have 3 conditional scenarios:
return 1 if positive, 0 if zero, and -1 if negative.

我当时想为了正确执行此操作,我需要使用!运算符以及!0x<nonzero #>=0!0x0=1!0x1=0的事实.

I was thinking that in order to do this properly, I need to use ! operator and the fact that !0x<nonzero #>=0, !0x0=1, !0x1=0.

所以我想出了类似这样的东西,这是不正确的:

So I came up with something like this, which is incorrect:

/*                                                                              
 * sign - return 1 if positive, 0 if zero, and -1 if negative                   
 *  Examples: sign(130) = 1                                                     
 *            sign(-23) = -1                                                    
 *  Legal ops: ! ~ & ^ | + << >>                                                                          
 */
int sign(int x) {
    return (x>>31) & -1 ) + ( !( !x >> 31 ) & 1;
}

我想我拥有所有作品,但不确定如何将它们放在一起.任何帮助表示赞赏.

I think I have all the pieces but just not quite sure how to put them all together. Any help is appreciated.

谢谢.

推荐答案

位黑客页面建议使用以下表达式:

The bit hacks page suggests this expression:

sign = (v != 0) | (v >> 31);

无需!=即可重写,如下所示:

It can be rewritten without != like this:

sign = (!!v) | (v >> 31);

( demo ).

不过,我更喜欢这种不使用位操作的表达式(在同一页面上).

I prefer this expression that does not use bit manipulation, though (from the same page).

sign = (v > 0) - (v < 0);

这篇关于仅使用位运算符在C中对符号函数进行签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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