【CS61C】Lab2 实验解析
凌晨九点 Lv2

前言

本人学习的是 2020 fall版的CS61C,本文将对Lab2解题思路做大致介绍,具体代码可以参考我的仓库

解题思路

Exercise 1: Bit Operations

三道位运算的题目中值得一说的是第二道,函数接口如下

1
2
3
// Set the nth bit of the value of x to v.
// Assume 0 <= n <= 31, and v is 0 or 1
void set_bit(unsigned * x, unsigned n, unsigned v);

题目限制如下

You may ONLY use bitwise operations such as and (&), or (|), xor (^), not (~), left shifts («), and right shifts (»). You may not use any for/while loops or conditional statements. You also may not use modulo (%), division, addition subtraction, or multiplication for this question.

我的解题思路是:

  1. 首先分析只有当需要变化的位xnx_nnn不同时才会发生改变。
  2. 需要通过位运算找到位反转的方式和判断不同的方式
  3. 位反转:通过异或实现
  4. 判断不同: 通过移位到最低位比较得到

具体代码如下

1
2
3
4
void set_bit(unsigned * x, unsigned n, unsigned v) {
unsigned bit = ((*x) >> n) & 1;
(*x) ^= ((bit ^ v) << n);
}