位操作的一个实验题
来源:互联网 发布:情侣 第一次旅游 知乎 编辑:程序博客网 时间: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
- 位操作的一个实验题
- GPIO实验 位操作
- 一个位操作的小技巧
- Java位操作的一个例子
- 一个位操作函数
- 位段的小实验
- 位操作循序渐进一(获得一个整数的符号)
- C/C++ 位操作实例:输出一个数的二进制
- 【C语言】判断一个数的奇偶(位操作)
- 不用任何位操作,获得一个int变量的第九位
- 图的操作实验
- 一个实验的结束
- 一个java的实验
- bgp的一个实验
- isis的一个实验
- 一道位操作的趣味编程题
- 简单的位操作
- C的位操作
- 黑马程序员_Eclipse使用及其常用快捷键
- java迭代器
- mysql存储过程 在动态SQL内获取返回值
- 康拓展开
- 如何设置进程(线程)在指定的CPU上运行
- 位操作的一个实验题
- VS2005 操作快捷键
- 康拓展开逆运算
- Backbone.js 0.9.2 中文解释
- 面向程序员的数据库访问性能优化法则
- 黑马程序员_API使用及常见API类中的方法
- VC 双缓冲图形刷新技术
- Maven之应用
- css布局 居中总结