位操作的一个实验题

来源:互联网 发布:情侣 第一次旅游 知乎 编辑:程序博客网 时间:2024/05/16 00:47

我们都知道位运算的速度很快,在写程序的时候,如果能够将一些操作转化为位运算将是一件很happy的事情。

笔者在此之前做了一个位操作的实验,现将题目贴出,答案附在后面,有兴趣的可以做一下:)

实验来自SSD6

实验要求:

比如:意思很好理解的,这里就不详细写了,但是一定要看每道题的注释中的要求

  /*
   * pow2plus1 - returns 2^x + 1, where 0 <= x <= 31
   */
  int pow2plus1(int x) { //x*2+1
     /* exploit ability of shifts to compute powers of 2 */
     return (1 << x) + 1;
  }



int bitAnd(int x, int y) {}/*  * bitOr - x|y using only ~ and &                      *   Example: bitOr(6, 5) = 7 *   Legal ops: ~ & *   Max ops: 8 *   Rating: 1 */int bitOr(int x, int y) {}/* * isZero - returns 1 if x == 0, and 0 otherwise  *   Examples: isZero(5) = 0, isZero(0) = 1 *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 2 *   Rating: 1 */int isZero(int x) {}/*  * minusOne - return a value of -1  *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 2 *   Rating: 1 */int minusOne(void) {}/*  * TMax - return maximum two's complement integer  *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 4 *   Rating: 1 */int tmax(void) {}/*  * bitXor - x^y using only ~ and &  *   Example: bitXor(4, 5) = 1 *   Legal ops: ~ & *   Max ops: 14 *   Rating: 2 */int bitXor(int x, int y) {}/*  * getByte - Extract byte n from word x *   Bytes numbered from 0 (LSB) to 3 (MSB) *   Examples: getByte(0x12345678,1) = 0x56 *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 6 *   Rating: 2 */int getByte(int x, int n) {}/*  * isEqual - return 1 if x == y, and 0 otherwise  *   Examples: isEqual(5,5) = 1, isEqual(4,5) = 0 *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 5 *   Rating: 2 */int isEqual(int x, int y) {}/*  * negate - return -x  *   Example: negate(1) = -1. *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 5 *   Rating: 2 */int negate(int x) {}/*  * isPositive - return 1 if x > 0, return 0 otherwise  *   Example: isPositive(-1) = 0. *   Legal ops: ! ~ & ^ | + << >> *   Max ops: 8 *   Rating: 3 */int isPositive(int x) {}


解析

——————————————————————————————————————————————————————————————————————————




1、bitAnd:  return ~(~x|~y);

2、bitOr :return ~(~x&~y);

3、isZero:return !x;

4、minusOne:return ~1+1;
5、tmax:return ~(1<<31);//注意逻辑右移和算术右移之间的区别

6、bitXor:return ~((~(~x&y))&(~(x&~y))); //x^y=(~x&y)|(x&~y);

7、getByte:return (x>>(n<<3))&0xff;//一个字节有8个bits

8、isEqual:return !(x^y);

9、netate:return ~x+1;//取反加1

10、isPositive:return !(x>>31)&(!!x);//注意当遇到0的时候怎么办,0是非正数


0 0
原创粉丝点击