csapp lab1 data-lab记录(二)

 5.negate
 
 /* negate - return -x 
 *   Example: negate(1) = -1.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 5
 *   Rating: 2
 */
int negate(int x) {
  return ~x + 1;
}
6.isAsciiDigit
/* 
 * isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
 *   Example: isAsciiDigit(0x35) = 1.
 *            isAsciiDigit(0x3a) = 0.
 *            isAsciiDigit(0x05) = 0.
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 15
 *   Rating: 3
 */
int isAsciiDigit(int x) {
 
    return !((x + ~0x30)>>31) | ((0x39 + ~x)>>31));

}

思路:

x-0x30>=0------>(x+~0x30)=a

0x39-x>=0------>(0x39+~x)=b

此时我们只需要判断符号位了,当a,b均大于等于0时,a和b的符号位肯定为0。所以我们分别将a,b右移31位,当a,b均为0时,判断为真。

7. conditional
/* 
 * conditional - same as x ? y : z 
 *   Example: conditional(2,4,5) = 4
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 16
 *   Rating: 3
 */
int conditional(int x, int y, int z) {
  
    int mask = ((!! x)<<31)>>31
    return (~mask & z) | (mask & y);
}

思路:

a = !! x

b = ((x<<31)>>31)

1. x = 0, b = 0;

2. x != 0, b = 1111111111;

“掩码”

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值