位操作和转移 [英] Bitwise operations and shifts

查看:121
本文介绍了位操作和转移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林有一些麻烦了解如何以及为什么code工作它的方式。我在这个任务完成合作这部分,我不能让阿霍德他找出如何以及为什么这个工程。我已经尝试了一些不同的东西不懂,但任何帮助将是非常美联社preciated。这code是用2的补数和一个32位再presentation。

  / *
 * fitsBits - 返回1,如果x可以被重新presented作为
 * n位,补整数。
 * 1< = N< = 32
 *实施例:fitsBits(5,3)= 0,fitsBits(-4,3)= 1
 *法律OPS! 〜&安培; ^ | + LT;< >>
 *最大OPS:15
 *评级:2
 * /
INT fitsBits(INT X,INT N){
    INT R,C;
    C = 33 +〜N;
    !R =(((X&所述; c为C)GT;&℃)^ x的);
    返回ř;
}


解决方案

  C = 33 +〜N;

此计算许多高位如何使用后剩余 N 低位。

 ((X<< C)>>Ç

这零出的高位。

 !(^嗒嗒X)

这相当于

 等等==点¯x

Im having some trouble understanding how and why this code works the way it does. My partner in this assignment finished this part and I cant get ahold of him to find out how and why this works. I've tried a few different things to understand it, but any help would be much appreciated. This code is using 2's complement and a 32-bit representation.

/* 
 * fitsBits - return 1 if x can be represented as an 
 *  n-bit, two's complement integer.
 *   1 <= n <= 32
 *   Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 2
 */
int fitsBits(int x, int n) {
    int r, c;
    c = 33 + ~n;
    r = !(((x << c)>>c)^x);
    return r;
}

解决方案

c = 33 + ~n;

This calculates how many high order bits are remaining after using n low order bits.

((x << c)>>c

This zeros out the high order bits.

!(blah ^ x)

This is equivalent to

blah == x

这篇关于位操作和转移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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