今年四门必修课,英语写作、SSD4、SSD6还有解释器构造。难易程度跨度很大啊。SSD4的练习就连我一天都可以做两个,SSD6是两天做一个就差不多了,至于解释器构造,哎,希望两个月能有所突破吧。
做exercise2的时候把我写的方法发给别人看,居然收到了表扬。特别贴出来,以示纪念。
题目是这样的:用位移运算实现10个方法
以下是我的解决方案。最得意的是isPositive方法了,嘿嘿。如果有更简单的麻烦知会我一声
/*
* bitAnd - x&y using only ~ and |
* Example: bitAnd(6, 5) = 4
* Legal ops: ~ |
* Max ops: 8
* Rating: 1
*/
int bitAnd(int x, int y) {
//用集合的公式:A//B=~(~A//~B)来类比位运算的“&”
int z= ~( ~x|~y);
return z;}
/*
* bitOr - x|y using only ~ and &
* Example: bitOr(6, 5) = 7
* Legal ops: ~ &
* Max ops: 8
* Rating: 1
*/
int bitOr(int x, int y) {
//用集合公式A//B=~(~A//~B)类比位运算 “|”
int z =~(~x&~y);
return z;}
/*
* 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) {
return !x;}
/*
* minusOne - return a value of -1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 2
* Rating: 1
*/
int minusOne(void) {
//-1的补码为1,1的补码即为-1
return ~0x1 + 1;}
/*
* TMax - return maximum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmax(void) {
//0x10000000 的反码是最大二进制数
return ~(0x1<<31);}
/*
* bitXor - x^y using only ~ and &
* Example: bitXor(4, 5) = 1
* Legal ops: ~ &
* Max ops: 14
* Rating: 2
*/
int bitXor(int x, int y) {
//用集合的观点 A抑或B = ~((A//~B)//(~A//B))
int a= x&~y;
int b=~x& y;
int c=~( ~ a & ~ b);
return c;}
/*
* 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) {
//将n*8
int a = n<<3;
//x左移n*8位,即n个字节,将需要的byte移到最低位的字节端。
int b = x>>a;
//用0xFF掩码取x的新值的最低字节。
int c = b & 0xFF;
return c;}
/*
* 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) {
//^ 运算将x和y的不同位置1,相同位置0,若x==y,则x^y=0x0 ,函数返回1,反之不为 0x0,函数返回0
int z=! ( x^y);
return z;}
/*
* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
//x的负即为x的补码所表示的值
int a = ~x + 0x1;
return a;}
/*
* isPositive - return 1 if x > 0, return 0 otherwise
* Example: isPositive(-1) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 3
*/
int isPositive(int x) {
//若x为非0,a=0,x为0,a=1
int a = !x;
//用b表示x的符号位,若x为负,b=1,x为正或0,b=0;
int b = x>>31;
//当x为positive时,c=b ^ a=0 ^ 0=0;x为负数或0时,c=b^a= 1^0=1 或 c=b^a=0^1=1;
int c = b ^ a;
//返回!c,使得,c=1时表示x为positive,c=0时x为非positive
return !c;}